Last active
December 3, 2015 09:35
-
-
Save sodre/a4a15ba97ef104bab702 to your computer and use it in GitHub Desktop.
PKCS#12 to PEM Converter Context
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
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] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is how to use the Context and Converter work...