Self-signed SSL Certificate

Python code for dynamically creating a self-signed SSL Certificate.

C05348A3-9AB8-42C9-A6E0-81DB3AC59FEB
           

I originally gathered and wrote this code when I needed a large number of dynamically generated servers (an ASG) to register themselves so that I could connect to them from a central management server using gRPC. It is an awesome protocol but when using self-signed certificates, it did require the server's certificate to match the hostname.

So the code below was incorporated in the Python gRPC server code on all the nodes, each server in the ASG would create a new self-signed SSL certificate every time the process was started, and each server would register its presence and its public key into an ephemeral Zookeeper znode. That was an easy way to manage a large number of servers in that ASG.

Hope you find it useful!

import socket
from OpenSSL import crypto, SSL



def create_self_signed_cert(myHostName):
    """Create a self-signed certificate for the host."""
    # create a key pair
    k = crypto.PKey()
    k.generate_key(crypto.TYPE_RSA, 4096)

    # create a self-signed cert
    cert = crypto.X509()
    cert.get_subject().C = "US"
    cert.get_subject().ST = "NY"
    cert.get_subject().L = "Armonk"
    cert.get_subject().O = "IBM"
    cert.get_subject().OU = "Watson"
    cert.get_subject().CN = myHostName
    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')

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


myHostName = socket.gethostname().split('.')[0]
(certificate, privatekey) = create_self_signed_cert(myHostName)
print(certificate)
print(privatekey)
Posted Comments: 0

Tagged with:
encryption ssl