Create a self signed X509 certificate in Python
2012 August 5
Here is how to create a self signed certificate in Python using OpenSSL:
-
from OpenSSL import crypto, SSL
-
from socket import gethostname
-
from pprint import pprint
-
from time import gmtime, mktime
-
-
CERT_FILE = "selfsigned.crt"
-
KEY_FILE = "private.key"
-
-
def create_self_signed_cert():
-
-
# create a key pair
-
k = crypto.PKey()
-
k.generate_key(crypto.TYPE_<wbr>RSA, 1024)
-
-
# create a self-signed cert
-
cert = crypto.X509()
-
cert.get_subject().C = "UK"
-
cert.get_subject().ST = "London"
-
cert.get_subject().L = "London"
-
cert.get_subject().O = "Dummy Company Ltd"
-
cert.get_subject().OU = "Dummy Company Ltd"
-
cert.get_subject().CN = gethostname()
-
cert.set_serial_number(1000)
-
cert.gmtime_adj_notBefore(0)
-
cert.gmtime_adj_notAfter(10*<wbr>365*24*60*60)
-
cert.set_issuer(cert.get_<wbr>subject())
-
cert.set_pubkey(k)
-
cert.sign(k, 'sha1')
-
-
open(CERT_FILE, "wt").write(
-
crypto.dump_certificate(<wbr>crypto.FILETYPE_PEM, cert))
-
open(KEY_FILE, "wt").write(
-
crypto.dump_privatekey(crypto.<wbr>FILETYPE_PEM, k))
-
-
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:
-
f = open(CERT_FILE)
-
cert_buffer = f.read()
-
f.close()
-
-
from M2Crypto import RSA, X509
-
cert = X509.load_cert_string(cert_<wbr>buffer, X509.FORMAT_PEM)
-
pub_key = cert.get_pubkey()
-
rsa_key = pub_key.get_rsa()
-
cipher = rsa_key.public_encrypt('<wbr>plaintext', RSA.pkcs1_padding)
-
-
print cipher
-
-
ReadRSA = RSA.load_key(KEY_FILE)
-
try:
-
plaintext = ReadRSA.private_decrypt (cipher, RSA.pkcs1_padding)
-
except:
-
print "Error: wrong key?"
-
plaintext = ""
-
-
print plaintext
No comments yet