How to print public key from certificates using "cryptography" library in Python2?

Viewed 3005

I have to extract public key from .pem certificate using cryptography library in Python2 but am able to get only public key object .

In cryptography documentation , I found this code

from cryptography.hazmat.primitives.asymmetric import rsa

pem_cert=open("/home/lab14/aes/fd.pem","rb").read()

cert = x509.load_pem_x509_certificate(pem_cert, default_backend())

public_key = cert.public_key()

print(public_key)

But when run this, I get public key object but not actual key in hex format.

Here is the output I got

<cryptography.hazmat.backends.openssl.rsa._RSAPublicKey object at 0x7f49e214d6d8>

Any assistance would be helpful and appreciated . Thank you

2 Answers

You've got a public key object, which needs to be encoded to retrieve a representation of the key in bytes. Then those bytes can be encoded using any hexadecimal encoder - if that's what is required.

So simply call public_bytes(encoding, format) to retrieve the bytes. The encoding can be SubjectPublicKeyInfo, which contains information about the public key type (it's a generic key) or PKCS1, which basically contains a minimal encoding of the RSA public key. Note that you may first have to establish the key type before you can use PKCS1 because that only describes RSA keys.

You can also choose between DER and PEM format. DER just returns a byte representation of the ASN.1 defined structure of an RSA public key. PEM base 64 encodes that structure and adds header and footer lines as to create a textual representation of the key.

You don't really say what you want to print or why. If you just wanted to print the public exponent and modulus of an RSAPublicKey you can do:

public_key = cert.public_key()
print((public_key.public_numbers().e, public_key.public_numbers().n))
Related