Skip to content

Instantly share code, notes, and snippets.

@madhuri-rai07
Last active August 29, 2015 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save madhuri-rai07/5bbbba1c8e040dcb9199 to your computer and use it in GitHub Desktop.
Save madhuri-rai07/5bbbba1c8e040dcb9199 to your computer and use it in GitHub Desktop.
Tool to generate certificates
import os
import time
from M2Crypto import X509, EVP, RSA, ASN1
def make_ca_issuer():
"""
Creates Magnum default CA issuer name.
"""
issuer = X509.X509_Name()
#issuer.CN = cn
return issuer
def make_cert_valid(cert, days=365):
"""
Make a cert valid from now and til 'days' from now.
:args cert: certificate to make valid
:args days: number of days cert is valid for from now.
"""
t = long(time.time())
now = ASN1.ASN1_UTCTIME()
now.set_time(t)
expire = ASN1.ASN1_UTCTIME()
expire.set_time(t + days * 24 * 60 * 60)
cert.set_not_before(now)
cert.set_not_after(expire)
def make_request(bits, cn='localhost'):
"""
Create a X509 request with the given number of bits in they key.
:args bits: number of RSA key bits
:args cn: common name in the request
:returns: a X509 request and the private key (EVP)
"""
priv_key = EVP.PKey()
req = X509.Request()
rsa = RSA.gen_key(bits, 65537, lambda: None)
priv_key.assign_rsa(rsa)
req.set_pubkey(priv_key)
name = req.get_subject()
name.CN = cn
req.sign(priv_key,'sha1')
return req, priv_key
def make_cacert():
"""
Make a CA certificate.
:returns: certificate, private key and public key.
"""
req, priv_key = make_request(1024)
pub_key = req.get_pubkey()
cert = X509.X509()
make_cert_valid(cert)
cert.set_issuer(make_ca_issuer())
cert.set_subject(cert.get_issuer())
cert.set_pubkey(pub_key)
#cert.add_ext(X509.new_extension('basicConstraints', 'CA:TRUE'))
#cert.add_ext(X509.new_extension('subjectKeyIdentifier', cert.get_fingerprint()))
cert.sign(priv_key, 'sha1')
return cert, priv_key, pub_key
def make_cert():
"""
Make a certificate.
Returns a new cert.
"""
cert = X509.X509()
make_cert_valid(cert)
cert.add_ext(X509.new_extension('nsComment', 'SSL sever'))
return cert
def make_ca_signed_cert(cacert_file, ca_key_file, cn):
"""
Create a certificate signed by the given CA, and with the given
common name. And stores the file at given location with given name.
:param cacert_file: CA certificate file
:param ca_key_file: CA private key file
:param cn: desired common name
:returns: certificate and private key
"""
cert_req, priv_key = make_request(1024, cn=cn)
cacert = X509.load_cert(cacert_file)
ca_priv_key = EVP.load_key(ca_key_file)
cert = make_cert()
cert.set_subject(cert_req.get_subject())
cert.set_pubkey(cert_req.get_pubkey())
cert.set_issuer(cacert.get_issuer())
cert.sign(ca_priv_key, 'sha1')
return cert, priv_key
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment