Generating a CSR in Python

≯℡__Kan透↙ 提交于 2019-12-06 06:04:22

I assume you don't want to use the command line openssl itself and a Python lib is ok.

Here is an helper function I wrote to create a CSR. It returns the private key from the generated key pair and the CSR. The function depends on pyOpenSSL.crypto.

def create_csr(self, common_name, country=None, state=None, city=None,
               organization=None, organizational_unit=None,
               email_address=None):
    """
    Args:
        common_name (str).

        country (str).

        state (str).

        city (str).

        organization (str).

        organizational_unit (str).

        email_address (str).

    Returns:
        (str, str).  Tuple containing private key and certificate
        signing request (PEM).
    """
    key = OpenSSL.crypto.PKey()
    key.generate_key(OpenSSL.crypto.TYPE_RSA, 2048)

    req = OpenSSL.crypto.X509Req()
    req.get_subject().CN = common_name
    if country:
        req.get_subject().C = country
    if state:
        req.get_subject().ST = state
    if city:
        req.get_subject().L = city
    if organization:
        req.get_subject().O = organization
    if organizational_unit:
        req.get_subject().OU = organizational_unit
    if email_address:
        req.get_subject().emailAddress = email_address

    req.set_pubkey(key)
    req.sign(key, 'sha256')

    private_key = OpenSSL.crypto.dump_privatekey(
        OpenSSL.crypto.FILETYPE_PEM, key)

    csr = OpenSSL.crypto.dump_certificate_request(
               OpenSSL.crypto.FILETYPE_PEM, req)

    return private_key, csr

m2crypto could be a solution (see CreateX509Request in the contrib example), although it relies OpenSSL.

You could also use python-nss, which uses Mozilla's NSS library. nss.nss.CertificateRequest was added quite recently. The API documentation available at the moment on the website isn't up to date, but here are some pointers for newer versions:

It's also in CVS:

:pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot/mozilla/security/python/nss 

I started to implement a CSR generator using PyCrypto and PyASN1 during the last few days. The first code is available at https://github.com/jandd/python-pkiutils

Like any language, Python just implements algorithms. I know next to nothing about cryptography, but if I had to implement this in Python, I would look for a specification on how to implement CSR.

Via Google and Wikipedia I found this RFC. Your task would be to implement this in Python.

Personally I'd probably first try to use a the command line tool (perhaps via a call to the system() function if it needed to be from Python).

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!