Skip to content

Instantly share code, notes, and snippets.

@imankulov
Last active August 29, 2015 14:07
Show Gist options
  • Save imankulov/4cd2aebb341bb8b38704 to your computer and use it in GitHub Desktop.
Save imankulov/4cd2aebb341bb8b38704 to your computer and use it in GitHub Desktop.
Convert PKCS#12 certificate and key files to PEM
#!/usr/bin/env python
"""
Quick, dirty and insecure tool to extract certificate info and private key
from the PKCS#12 certicate and dump it to separate files in PEM format
(because openssl command-line tool is a mess)
Usage: p12_to_pem path/to/file.p12 password
"""
import os
import sys
from OpenSSL.crypto import load_pkcs12, dump_certificate, dump_privatekey, FILETYPE_PEM
try:
password = sys.argv[2]
p12_file = sys.argv[1]
except IndexError:
raise SystemExit(__doc__)
cert_file = '%s.pem' % os.path.splitext(p12_file)[0]
key_file = '%s.key' % os.path.splitext(p12_file)[0]
p12 = load_pkcs12(open(p12_file, 'rb').read(), password)
with open(cert_file, 'wb') as fd:
fd.write(dump_certificate(FILETYPE_PEM, p12.get_certificate()))
print cert_file
with open(key_file, 'wb') as fd:
fd.write(dump_privatekey(FILETYPE_PEM, p12.get_privatekey()))
print key_file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment