M2Crypto CA example

Conrad Steenberg <[email protected]>
Newsgroups gmane.comp.python.cryptography
Message-ID <[email protected]>
Hi

In my previous message I sent a couple of patches that claimed to make
it possible to use M2Crypto as a Certificate Authority (CA).

Attached is an example to show how this can be done for the public
record :-)

Cheers

Conrad
test_cert.py (application/x-python, 1.6 KB)
import time
from M2Crypto import *

# Load the CA certificate and private key
ca_cert=X509.load_cert("cacert.pem")
ca_pub_key=ca_cert.get_pubkey()
ca_pub_rsa=RSA.RSA_pub(m2.rsa_from_pkey(ca_pub_key))
ca_priv_rsa=RSA.load_key("cakey.pem")

# Generate a new keypair and assign the public key to a new X509 cert
newrsa=RSA.gen_key(512,65537)
newevp=EVP.PKey()
newevp.assign_rsa(newrsa)
newx509=X509.X509()
newx509.set_pubkey(newevp)
newx509.set_issuer_name(ca_cert.get_subject().x509_name)

# Create a new X509_Name object for our new certificate
x509_name=X509.X509_Name()
x509_name.O="MyOrg"
x509_name.OU="MyUnit"
x509_name.Email="[email protected]"
x509_name.CN="My Real Name"

# Set the new cert subject
newx509.set_subject_name(x509_name.x509_name)

# Create EVP objects from the CA keypair
ca_pub_evp=EVP.PKey()
ca_pub_evp.assign_rsa(ca_pub_rsa)

ca_priv_evp=EVP.PKey()
ca_priv_evp.assign_rsa(ca_priv_rsa)


# Set Cert version
newx509.set_version(3)

# Set Cert validity time
now=ASN1.ASN1_UTCTIME()
now.set_time(int(time.time()))
later=ASN1.ASN1_UTCTIME()
later.set_time(int(time.time()+3600*24*7))

newx509.set_not_before(now.asn1_utctime)
newx509.set_not_after(later.asn1_utctime)


# Set serial number
serial=m2.asn1_integer_new()
m2.asn1_integer_set(serial,20)
m2.x509_set_serial_number(newx509.x509,serial)

# Sign the new certificate!
newx509.sign(ca_priv_evp,"sha1")
print m2.x509_verify(newx509.x509, m2.x509_get_pubkey(ca_cert.x509))

# Print the new certificate as a PEM-encoded string
print newx509.as_pem()

# Print the new private key as a PEM-encoded (but unencrypted) string
print newrsa.as_pem(cipher=None)
smime.p7s (application/x-pkcs7-signature, 2.5 KB) - not displayed
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.