Skip to content

Instantly share code, notes, and snippets.

@sodre
Last active December 3, 2015 09:35
Show Gist options
  • Save sodre/a4a15ba97ef104bab702 to your computer and use it in GitHub Desktop.
Save sodre/a4a15ba97ef104bab702 to your computer and use it in GitHub Desktop.
PKCS#12 to PEM Converter Context
class context:
def __init__(self, pkcs12, password=None, separate_key=False):
from OpenSSL.crypto import load_pkcs12
from getpass import getpass
from os.path import basename
if not password:
prompt = '{} Password: '.format(basename(pkcs12))
password = getpass(prompt)
with open(pkcs12, 'rb') as f:
self.__p12 = load_pkcs12(f.read(), password)
self.separate_key = separate_key
def __enter__(self):
from OpenSSL.crypto import dump_privatekey, dump_certificate
from OpenSSL.crypto import FILETYPE_PEM
from tempfile import NamedTemporaryFile
# Write the Private Key.
self._key = NamedTemporaryFile(suffix='.pem')
self._key.write(dump_privatekey(FILETYPE_PEM,
self.__p12.get_privatekey()))
# Write the Cert and CA Chain (if available)
crt_chain = [self.__p12.get_certificate()]
if self.__p12.get_ca_certificates():
crt_chain += list(self.__p12.get_ca_certificates())
if self.separate_key:
self._cert = NamedTemporaryFile(suffix='.pem')
else:
self._cert = self._key
for crt in crt_chain:
self._cert.write(dump_certificate(FILETYPE_PEM, crt))
self._key.file.close()
self._cert.file.close()
return (self._cert.name, self._key.name) if self.separate_key else self._key.name
def __exit__(self, type, value, traceback):
self._key.close()
if self.separate_key:
self._cert.close()
self._key, self._cert = (None, None)
class converter:
def __init__(self, pkcs12, password=None):
self.__ctxt = context(pkcs12, password, separate_key=True)
self.pem_files = self.__ctxt.__enter__()
def __delete__(self):
self.__ctxt.__exit__()
def __len__(self):
return len(self.pem_files)
def __getitem__(self, i):
return self.pem_files[i]
@sodre
Copy link
Author

sodre commented Nov 30, 2015

This is how to use the Context and Converter work...

from pkcs12_as_pem import context as pkcs12_as_pem_ctx
from pkcs12_as_pem import converter as p12_as_pem_conv
from os import path
import gc


p12_filepath="<path to pkcs#12>"


# Context Version
with pkcs12_as_pem_ctx(p12_filepath) as pem_path:
    assert(path.exists(pem_path))
assert(not path.exists(pem_path))


# Object Version
pem = p12_as_pem_conv(p12_filepath)

pem_path = pem.pem_file_path
assert(path.exists(pem_path))
del(pem)

#After GC collection Runs...
gc.collect()
assert(not path.exists(pem_path))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment