Skip to content

Instantly share code, notes, and snippets.

@markscottwright
Last active October 19, 2017 19:01
Show Gist options
  • Save markscottwright/5f20bfd3be83f7e6280e0a84e16736cc to your computer and use it in GitHub Desktop.
Save markscottwright/5f20bfd3be83f7e6280e0a84e16736cc to your computer and use it in GitHub Desktop.
How to create a self-signed certificate in Python

How to create a self-signed certificate in Python

I used to have a Word Press blog (I suppose I still do) and this was by far my most popular post. (A quick google search showed my code in a bunch of projects).

Often times, you need a keypair and certificate for a website, but you don't need it to be signed by a recognized CA. Here's how to do that in python. Note that the method below isn't the most current, since it's using the common name component of the certificate's Subject as the hostname, instead of the Subject Alternative Name. See rfc2818 for more information.

from socket import gethostname
from OpenSSL import crypto

def get_self_signed_cert(hostname, serialnumber):
    """
    Create a self-signed certificate and return it and the private key in PEM format
    """

    # create a key pair
    k = crypto.PKey()
    k.generate_key(crypto.TYPE_RSA, 4096)

    # create a self-signed cert - the attributes below, other than CN, can be omitted
    cert = crypto.X509()
    cert.get_subject().C = "Your Country"
    cert.get_subject().ST = "Your State"
    cert.get_subject().L = "Your City"
    cert.get_subject().O = "Your company"   
    cert.get_subject().OU = "Your department"
    cert.get_subject().CN = hostname
    cert.set_serial_number(serialnumber)
    cert.gmtime_adj_notBefore(0)
    cert.gmtime_adj_notAfter(10*365*24*60*60)
    cert.set_issuer(cert.get_subject())
    cert.set_pubkey(k)
    cert.sign(k, 'sha256')

    return (crypto.dump_certificate(crypto.FILETYPE_PEM, cert),
            crypto.dump_privatekey(crypto.FILETYPE_PEM, k))

crt, private_key = get_self_signed_cert(gethostname(), 1)
print(crt.decode("utf-8"))
print(private_key.decode("utf-8"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment