Search code examples
python-3.xcertificatex509certificatepublic-keypem

Python print all public key certificate information (X.509 Format)


I am trying to write a Python3 program which will show me all information which is included in a public key certificate, similar to the following linux command:

openssl x509 -in website.com.pem -text

which will return a result similar to

Certificate:
Data:
    Version: 3 (0x2)
    Serial Number:
        04:7a:f7:95:47:c0:7d:0f:ef:80:a5:b2:1f:51:e3:63
Signature Algorithm: sha256WithRSAEncryption
    Issuer: C = GB, ST = Greater Manchester, L = Salford, O = COMODO CA Limited, CN = COMODO RSA Domain Validation Secure Server CA
    Validity
        Not Before: Mar 12 00:00:00 2018 GMT
        Not After : Mar 11 23:59:59 2020 GMT
    Subject: OU = Domain Control Validated, OU = PositiveSSL, CN = acs.cdroutertest.com
    Subject Public Key Info:
        Public Key Algorithm: rsaEncryption
            Public-Key: (2048 bit)

as shown on the following website: https://support.qacafe.com/knowledge-base/how-do-i-display-the-contents-of-a-ssl-certificate/

I was trying the Cryptography or pyopenssl modules in python3 already, and was able to import the certificate and display e.g. the public key. However i did not find a way to go through all information available and just display them, without having to write a print() statement for every field that might or might not be available in the certificate.

Does anybody have an idea how to push me into the right direction?

Its appreciated, thank you!


Solution

  • A solution that has actually slipped my attention is the use of the module asn1tools

    import asn1tools
    foo = asn1tools.compile_files("x509.asn")
    output = foo.decode("Certificate", cert)
    

    Only all ASN.1 definitions needed for X509 have to be available in the file x509.asn (available via the respective RFC), while "cert" holds the bytestring.

    The result will be a python dict with all the information contained, without having to loop through anything or missing some unusual parameters