Skip to content

Instantly share code, notes, and snippets.

@William-Hill
Created July 2, 2018 17:11
Show Gist options
  • Save William-Hill/274427a728d9632ec3882ba1f21c7ad8 to your computer and use it in GitHub Desktop.
Save William-Hill/274427a728d9632ec3882ba1f21c7ad8 to your computer and use it in GitHub Desktop.
Create a self-signed cert using PyOpenSSL
def create_self_signed_cert(cert_dir):
"""
If datacard.crt and datacard.key don't exist in cert_dir, create a new
self-signed cert and keypair and write them into that directory.
Source: https://skippylovesmalorie.wordpress.com/2010/02/12/how-to-generate-a-self-signed-certificate-using-pyopenssl/
"""
CERT_FILE = "hostcert.pem"
KEY_FILE = "hostkey.pem"
if not os.path.exists(os.path.join(cert_dir, CERT_FILE)) \
or not os.path.exists(os.path.join(cert_dir, KEY_FILE)):
# create a key pair
k = OpenSSL.crypto.PKey()
k.generate_key(OpenSSL.crypto.TYPE_RSA, 4096)
# create a self-signed cert
cert = OpenSSL.crypto.X509()
cert.get_subject().C = "US"
cert.get_subject().ST = "California"
cert.get_subject().L = "Livermore"
cert.get_subject().O = "LLNL"
cert.get_subject().OU = "ESGF"
cert.get_subject().CN = socket.gethostname()
cert.set_serial_number(1000)
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, 'sha1')
pybash.mkdir_p(cert_dir)
with open(os.path.join(cert_dir, CERT_FILE), "wt") as cert_file_handle:
cert_file_handle.write(OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, cert))
with open(os.path.join(cert_dir, KEY_FILE), "wt") as key_file_handle:
key_file_handle.write(OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, k))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment