Search code examples
pythonopensslpycrypto

Extract public-key modulus from PrivateKey/CertificateRequest/Certificate in Python , with the same format as OpenSSL


using OpenSSL, i can extract the modulus of the public key from various objects with these commands:

openssl rsa -noout -modulus -in {KEY}
openssl req -noout -modulus -in {CSR}
openssl x509 -noout -modulus -in {CERT}

I am trying to replicate this within python, using cryptography or the pyopenssl package.

I can extract the public key from all of these objects in Python, but I can not figure out how to encode the modulus to match the OpenSSL commandline output -- which appears to be a base64 encoded version of a format that I can't figure out from the docs or source code of any of the 3 projects.


Solution

  • The RSAPublicNumbers class (link) in cryptography has what you are looking for. You can get it using to_cryptography_key method (link) of PKey class in pyopenssl.

    from OpenSSL.crypto import load_certificate
    from OpenSSL.crypto import FILETYPE_PEM
    
    with open(certfile, 'rb') as fp:
        cert = load_certificate(FILETYPE_PEM, fp.read())
    
    # This gives you the modulus in integer form
    modn = cert.get_pubkey().to_cryptography_key().public_numbers().n
    
    # Convert it to hex
    print('{:X}'.format(modn))