Created
August 23, 2011 12:58
-
-
Save ril3y/1165038 to your computer and use it in GitHub Desktop.
Python script that will generate a x.509 certificate
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
from OpenSSL import crypto, SSL | |
from socket import gethostname | |
from pprint import pprint | |
from time import gmtime, mktime | |
from os.path import exists, join | |
CERT_FILE = "myapp.crt" | |
KEY_FILE = "myapp.key" | |
def create_self_signed_cert(cert_dir): | |
""" | |
If datacard.crt and datacard.key don't exist in cert_dir, create a new | |
self-signed cert and keypair and write them into that directory. | |
""" | |
if not exists(join(cert_dir, CERT_FILE)) \ | |
or not exists(join(cert_dir, KEY_FILE)): | |
# create a key pair | |
k = crypto.PKey() | |
k.generate_key(crypto.TYPE_RSA, 1024) | |
# create a self-signed cert | |
cert = crypto.X509() | |
cert.get_subject().C = "US" | |
cert.get_subject().ST = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" | |
cert.get_subject().L = "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" | |
cert.get_subject().O = "CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC" | |
cert.get_subject().OU = "my organization" | |
cert.get_subject().CN = "DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD" | |
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') | |
open(join(cert_dir, CERT_FILE), "wt").write( | |
crypto.dump_certificate(crypto.FILETYPE_PEM, cert)) | |
open(join(cert_dir, KEY_FILE), "wt").write( | |
crypto.dump_privatekey(crypto.FILETYPE_PEM, k)) | |
create_self_signed_cert(".") |
Nice source, but today fails. Need to update line 38, and change algorithm to sign the certificate, change from sha1 to sha256 will fix this code.
Old:
cert.sign(k, 'sha1')
New:
cert.sign(k, 'sha256')
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The certificate generated is corrupted.
$ openssl x509 -in myapp.crt -text -noout
unable to load certificate
4294956672:error:0D0C40D8:asn1 encoding routines:c2i_ASN1_OBJECT:invalid object encoding:a_object.c:287:
4294956672:error:0D08303A:asn1 encoding routines:ASN1_TEMPLATE_NOEXP_D2I:nested asn1 error:tasn_dec.c:699:Field=algorithm, Type=X509_ALGOR
4294956672:error:0D08303A:asn1 encoding routines:ASN1_TEMPLATE_NOEXP_D2I:nested asn1 error:tasn_dec.c:699:Field=signature, Type=X509_CINF
4294956672:error:0D08303A:asn1 encoding routines:ASN1_TEMPLATE_NOEXP_D2I:nested asn1 error:tasn_dec.c:699:Field=cert_info, Type=X509
4294956672:error:0906700D:PEM routines:PEM_ASN1_read_bio:ASN1 lib:pem_oth.c:83: