Search code examples
pythonssl-certificatepublic-key

Simple DER Cert Parsing in python


Which is the best way to parse with python a binary file with X509 Certificate in DER format to extract public key.


Solution

  • Neither the built-in SSL module of Python nor PyOpenSSL have an API to extract the private key and access its information. M2Crypto is no longer maintained and doesn't work with OpenSSL 1.0 and newer.

    PyOpenSSL has a public key class but its features are limited:

    >>> with open("cert.der", "rb") as f:
    ...     der = f.read()
    ... 
    >>> import OpenSSL.crypto
    >>> x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_ASN1, der)
    >>> pkey = x509.get_pubkey()
    >>> dir(pkey)
    ['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'bits', 'check', 'generate_key', 'type']
    >>> pkey.bits()
    4096L
    >>> pkey.type() == OpenSSL.crypto.TYPE_RSA
    True
    

    Python 3.4 may get a X509 type that exposes more information like SPKI.