Last active
January 23, 2025 20:25
-
Star
(136)
You must be signed in to star a gist -
Fork
(24)
You must be signed in to fork a gist
-
-
Save erikbern/756b1d8df2d1487497d29b90e81f8068 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 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
HI Shafique, yes i am using it in Azure Databricks and then i have uploaded certificate in my Azure keyvault certificate store.
and then here is my code
am i missing anything?