Skip to content

Instantly share code, notes, and snippets.

@avoidik
Created February 12, 2019 09:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save avoidik/232f016db57897c64ad35c01664f2660 to your computer and use it in GitHub Desktop.
Save avoidik/232f016db57897c64ad35c01664f2660 to your computer and use it in GitHub Desktop.
PKCS experiments
# load OpenSSL.crypto
from OpenSSL import crypto
# open it, using password. Supply/read your own from stdin.
p12 = crypto.load_pkcs12(open("/path/to/cert.p12", 'rb').read(), passwd)
# get various properties of said file.
# note these are PyOpenSSL objects, not strings although you
# can convert them to PEM-encoded strings.
p12.get_certificate() # (signed) certificate object
p12.get_privatekey() # private key.
p12.get_ca_certificates() # ca chain.
def pkcs12_to_pem(pkcs12_data, password):
# Old versions of OpenSSL.crypto.load_pkcs12() fail if the password is a unicode object
if isinstance(password, unicode):
password_bytes = password.encode('utf8')
else:
password_bytes = password
p12 = OpenSSL.crypto.load_pkcs12(pkcs12_data, password_bytes)
p12_cert = p12.get_certificate()
p12_key = p12.get_privatekey()
pem_cert = OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, p12_cert)
pem_key = OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, p12_key)
pem = pem_cert + pem_key
return pem
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment