Skip to content

Instantly share code, notes, and snippets.

@rohancme
Created October 5, 2018 19:09
Show Gist options
  • Save rohancme/d56456249b78208638029cad1837e192 to your computer and use it in GitHub Desktop.
Save rohancme/d56456249b78208638029cad1837e192 to your computer and use it in GitHub Desktop.
import random
from OpenSSL import crypto
ca_key = crypto.PKey()
ca_key.generate_key(crypto.TYPE_RSA, 4096)
ca_cert = crypto.X509()
ca_cert.set_version(2)
ca_cert.set_serial_number(random.randint(50000000, 100000000))
ca_subj = ca_cert.get_subject()
ca_subj.commonName = "This CA is my Root CA"
ca_cert.set_issuer(ca_subj)
ca_cert.set_pubkey(ca_key)
ca_cert.add_extensions([
crypto.X509Extension(b"subjectKeyIdentifier", False, b"hash", subject=ca_cert),
])
ca_cert.add_extensions([
crypto.X509Extension(b"authorityKeyIdentifier", False, b"keyid:always,issuer", issuer=ca_cert),
])
ca_cert.add_extensions([
crypto.X509Extension(b"basicConstraints", True, b"CA:TRUE"),
crypto.X509Extension(b"keyUsage", True, b"digitalSignature, keyCertSign, cRLSign"),
])
ca_cert.gmtime_adj_notBefore(0)
ca_cert.gmtime_adj_notAfter(365*24*60*60)
ca_cert.sign(ca_key, 'sha256')
# Save certificate
with open("ca.pem", "wt") as f:
f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, ca_cert).decode("utf-8"))
# Save private key
with open("ca.key", "wt") as f:
f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, ca_key).decode("utf-8"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment