Python: how to read a CSR file

In this article we will see how to extract the most relevant information from a CSR file with Python.

To get started, we need to install the pyOpenSSL module which provides an interface and wrapper classes around the OpenSSL library.

So we can define the following code:

import OpenSSL.crypto
from OpenSSL.crypto import load_certificate_request, FILETYPE_PEM

def get_csr_file(csr_file=None):
    if csr_file is None or not os.path.exists(csr_file):
        return None
    with open(csr_file, 'r') as crt:
        return crt.read()


def get_csr_data(file=None):
    csr = get_csr_file(file)
    if csr is None:
        return None
    csr_request = load_certificate_request(FILETYPE_PEM, csr)
    pub_key = csr_request.get_pubkey()
    pub_key_type = 'RSA' if pub_key.type() == OpenSSL.crypto.TYPE_RSA else 'DSA'
    pub_key_size = pub_key.bits()
    subject = csr_request.get_subject()
    components = dict(subject.get_components())
    return {
        'key_type': pub_key_type,
        'key_size': pub_key_size,
        'attributes': components
    }

We read the content of the CSR file as a string and pass it, if it exists, to the load_certificate_request() function together with the constant that specifies the type of certificate we want to parse. This function returns an object whose methods allow us to obtain the type of public key used, its size in bytes and the data contained in the certificate attributes, such as Country, State, the Common Name and others.

We can use our code as follows:

def main():
    csr_data = get_csr_data('./test.csr')
    print(csr_data)


if __name__ == '__main__':
    main()

Note that the data contained in the attributes dictionary is returned as bytes, so it will need to be converted to a string in order to display it in a web interface.

Back to top