I want to make a 'request' request, post, to a URL only that request needs to be signed. I can do it, passing the certificate in pfx and his password. But I want to do it by taking and using a certificate that is installed on the computer, on the Windows certmgr. How can I do this?
import requests
import base64
import contextlib
import OpenSSL.crypto
import tempfile
class Token():
def __init__(self, urlAuthenticate, consumer_key, consumer_secret, caminho_certificado_pfx, senha_certificado):
self.urlAuthenticate = urlAuthenticate
self.consumer_key = consumer_key
self.consumer_secret = consumer_secret
self.caminho_certificado_pfx = caminho_certificado_pfx
self.senha_certificado = senha_certificado
@contextlib.contextmanager
def carregarCertificado(self, caminho_certificado, senha_certificado):
with tempfile.NamedTemporaryFile(suffix='.pem', delete=False) as t_pem:
f_pem = open(t_pem.name, 'wb')
pfx = open(caminho_certificado, 'rb').read()
p12 = OpenSSL.crypto.load_pkcs12(pfx, senha_certificado)
f_pem.write(OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, p12.get_privatekey()))
f_pem.write(OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, p12.get_certificate()))
ca = p12.get_ca_certificates()
if ca is not None:
for cert in ca:
f_pem.write(OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, cert))
f_pem.close()
yield t_pem.name
def getChave(self):
chave = self.consumer_key + ':' + self.consumer_secret
chave_bytes = chave.encode('utf8')
chave_base64_bytes = base64.b64encode(chave_bytes)
chave_base64_string = chave_base64_bytes.decode('utf8')
return(chave_base64_string)
def getHeaders(self, chave):
headers = {
'Authorization': 'Basic ' + chave,
'role-type': 'TERCEIROS',
'content-type': 'application/x-www-form-urlencoded'
}
return headers
def getDados(self):
data = {'grant_type': 'client_credentials'}
return data
def gerarToken(self):
headers = self.getHeaders(self.getChave())
data = self.getDados()
with self.carregarCertificado(self.caminho_certificado_pfx, self.senha_certificado) as cert:
requisicao = requests.post(url=self.urlAuthenticate, headers=headers, cert=cert, data=data)
token = requisicao.json()
return(token)
token = Token('url/authenticate', 'cbaaaa', 'abcccccc', 'cert.pfx', '1234')
print(token.gerarToken())