Skip to content

Instantly share code, notes, and snippets.

@damienpontifex
Last active November 17, 2019 20:16
Show Gist options
  • Save damienpontifex/9c08c2ed1f7f1d223591691e1602dcfb to your computer and use it in GitHub Desktop.
Save damienpontifex/9c08c2ed1f7f1d223591691e1602dcfb to your computer and use it in GitHub Desktop.
Common OpenSSL
from OpenSSL import crypto
key = crypto.PKey()
key.generate_key(crypto.TYPE_RSA, 2048)
cert = crypto.X509()
subj = cert.get_subject()
subj.CN = "localhost"
cert.gmtime_adj_notAfter(365*24*60*60)
cert.set_pubkey(key)
cert.sign(key, 'sha1')
with open('key.cer', 'w') as f:
f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, key))
with open('certificate.cer', 'w') as f:
f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
# combine into PKCS#12 (P12) bundle
pfx = crypto.PKCS12()
pfx.set_privatekey(key)
pfx.set_certificate(cert)
pfxdata = pfx.export(passphrase=None)
with open('certificate.p12', 'wb') as f:
f.write(pfxdata)
# New self-signed certificate and write out private key and public
openssl req -newkey rsa:2048 -nodes -keyout key.cer -x509 -days 365 -subj '/CN=localhost' -out certificate.cer
# Inspect the certificate
openssl x509 -text -noout -in certificate.cer
# combine into PKCS#12 (P12) bundle (no password)
openssl pkcs12 -inkey key.cer -in certificate.cer -export -passout pass: -out certificate.p12
# PKCS#12 back to certificate and key
# Export key
openssl pkcs12 -in certificate.p12 -passin pass: -nodes -nocerts -out localhost_key.cer
# Export certificate
openssl pkcs12 -in certificate.p12 -passin pass: -nodes -nokeys -out localhost.cer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment