-
-
Save rochacbruno/5564a6f27166189c2844e6d615926740 to your computer and use it in GitHub Desktop.
How to use a .pfx file with Python requests – also works with .p12 files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import contextlib | |
import OpenSSL.crypto | |
import os | |
import requests | |
import ssl | |
import tempfile | |
@contextlib.contextmanager | |
def pfx_to_pem(pfx_path, pfx_password): | |
''' Decrypts the .pfx file to be used with requests. ''' | |
with tempfile.NamedTemporaryFile(suffix='.pem') as t_pem: | |
f_pem = open(t_pem.name, 'wb') | |
pfx = open(pfx_path, 'rb').read() | |
p12 = OpenSSL.crypto.load_pkcs12(pfx, pfx_password) | |
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 | |
# HOW TO USE: | |
# with pfx_to_pem('foo.pem', 'bar') as cert: | |
# requests.post(url, cert=cert, data=payload) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment