user2192774
user2192774

Reputation: 3907

How to extract RSA public exponent using python M2Crypto

I have the following piece of code that extract a host leaf certificate and the certificate RSA public key:

c = ssock.getpeercert(True)
x509 = M2Crypto.X509.load_cert_der_string(c)
publickey=x509.get_pubkey()
m=publickey.get_modulus()

I tried to find functions to extract the public exponent of the RSA key but I could not find any. Can you help me figure out how can I extract the public exponent of RSA public key?

EDIT: if not possible by M2Crypt. Please, point any other way.

EDIT 2: when I tried to load the cert as DER as:

key = RSA.importKey(publickey.as_der())

I got this error:

('file() argument 1 must be encoded string without NULL bytes, not str',)

I want to avoid saving the certs in the local system. I just wan to extract the info such as modulus and exponent. What I understand from the error is that the importKey function takes the aregument as DER file not string. Can you help me find a workaround?

Upvotes: 4

Views: 2098

Answers (1)

Jay Bosamiya
Jay Bosamiya

Reputation: 3209

This code should give you the modulus and public exponent:

import Crypto.PublicKey.RSA

c = ssock.getpeercert(True)
x509 = M2Crypto.X509.load_cert_der_string(c)
publickey = x509.get_pubkey()
key = Crypto.PublicKey.RSA.importKey(publickey.as_der())

modulus = key.n
public_exponent = key.e

Upvotes: 4

Related Questions