Create a self signed X509 certificate in Python

前端 未结 3 1892
时光说笑
时光说笑 2020-12-13 20:15

I followed this url to create a X509 certificate. And the code is:

from OpenSSL import crypto, SSL
from socket import gethostname
from pprint import pprint
f         


        
相关标签:
3条回答
  • 2020-12-13 20:37

    A version which works with python3

    from OpenSSL import crypto, SSL
    
    def cert_gen(
        emailAddress="emailAddress",
        commonName="commonName",
        countryName="NT",
        localityName="localityName",
        stateOrProvinceName="stateOrProvinceName",
        organizationName="organizationName",
        organizationUnitName="organizationUnitName",
        serialNumber=0,
        validityStartInSeconds=0,
        validityEndInSeconds=10*365*24*60*60,
        KEY_FILE = "private.key",
        CERT_FILE="selfsigned.crt"):
        #can look at generated file using openssl:
        #openssl x509 -inform pem -in selfsigned.crt -noout -text
        # create a key pair
        k = crypto.PKey()
        k.generate_key(crypto.TYPE_RSA, 4096)
        # create a self-signed cert
        cert = crypto.X509()
        cert.get_subject().C = countryName
        cert.get_subject().ST = stateOrProvinceName
        cert.get_subject().L = localityName
        cert.get_subject().O = organizationName
        cert.get_subject().OU = organizationUnitName
        cert.get_subject().CN = commonName
        cert.get_subject().emailAddress = emailAddress
        cert.set_serial_number(serialNumber)
        cert.gmtime_adj_notBefore(0)
        cert.gmtime_adj_notAfter(validityEndInSeconds)
        cert.set_issuer(cert.get_subject())
        cert.set_pubkey(k)
        cert.sign(k, 'sha512')
        with open(CERT_FILE, "wt") as f:
            f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert).decode("utf-8"))
        with open(KEY_FILE, "wt") as f:
            f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, k).decode("utf-8"))
    
    cert_gen()
    
    0 讨论(0)
  • 2020-12-13 20:44

    Just remove <wbr>. So stupid I am.

    0 讨论(0)
  • 2020-12-13 20:50

    This is a really useful question; as the referenced link is now dead; and this is one of the first results for searching for "python create ssl certificate".

    I would add to it though, that "open(xxx, "wt").write()" is asking for problems later. By not explicitly closing the file, you may find that the garbage collector hasn't run when you try to actually use the file - resulting in a failure.

    it's better to use:

    with open(xxx, "w") as f:
        f.write()
    

    which will ensure that the file is closed when you're done.

    0 讨论(0)
提交回复
热议问题