Skip to content

Create a self signed X509 certificate in Python

2012 August 5

Here is how to create a self signed certificate in Python using OpenSSL:

  1. from OpenSSL import crypto, SSL
  2. from socket import gethostname
  3. from pprint import pprint
  4. from time import gmtime, mktime
  5.  
  6. CERT_FILE = "selfsigned.crt"
  7. KEY_FILE = "private.key"
  8.  
  9. def create_self_signed_cert():
  10.             
  11.         # create a key pair
  12.         k = crypto.PKey()
  13.         k.generate_key(crypto.TYPE_<wbr>RSA, 1024)
  14.  
  15.         # create a self-signed cert
  16.         cert = crypto.X509()
  17.         cert.get_subject().C = "UK"
  18.         cert.get_subject().ST = "London"
  19.         cert.get_subject().L = "London"
  20.         cert.get_subject().O = "Dummy Company Ltd"
  21.         cert.get_subject().OU = "Dummy Company Ltd"
  22.         cert.get_subject().CN = gethostname()
  23.         cert.set_serial_number(1000)
  24.         cert.gmtime_adj_notBefore(0)
  25.         cert.gmtime_adj_notAfter(10*<wbr>365*24*60*60)
  26.         cert.set_issuer(cert.get_<wbr>subject())
  27.         cert.set_pubkey(k)
  28.         cert.sign(k, 'sha1')
  29.  
  30.         open(CERT_FILE, "wt").write(
  31.             crypto.dump_certificate(<wbr>crypto.FILETYPE_PEM, cert))
  32.         open(KEY_FILE, "wt").write(
  33.             crypto.dump_privatekey(crypto.<wbr>FILETYPE_PEM, k))
  34.  
  35. create_self_signed_cert()

You can then use m2crypto library to encrypt and decrypt data using this self signed certificate. You use public key to encrypt and private key to decrypt:

  1. f = open(CERT_FILE)
  2. cert_buffer = f.read()
  3. f.close()
  4.  
  5. from M2Crypto import RSA, X509 
  6. cert = X509.load_cert_string(cert_<wbr>buffer, X509.FORMAT_PEM) 
  7. pub_key = cert.get_pubkey() 
  8. rsa_key = pub_key.get_rsa() 
  9. cipher = rsa_key.public_encrypt('<wbr>plaintext', RSA.pkcs1_padding)
  10.  
  11. print cipher
  12.  
  13. ReadRSA = RSA.load_key(KEY_FILE)
  14. try:
  15.     plaintext = ReadRSA.private_decrypt (cipher, RSA.pkcs1_padding)
  16. except:
  17.     print "Error: wrong key?"
  18.     plaintext = ""
  19.  
  20. print plaintext
No comments yet

Leave a Reply

Note: You can use basic XHTML in your comments. Your email address will never be published.

Subscribe to this comment feed via RSS