pythoncryptographyrsapublic-keypycrypto

How do you extract N and E from a RSA public key in python?


I have a RSA public key such that it looks like

-----BEGIN PUBLIC KEY-----
MIIBIDANBgkqhkiG9w0BAQEFAAOCAQ0AMIIBCAKCAQEAvm0WYXg6mJc5GOWJ+5jk
htbBOe0gyTlujRER++cvKOxbIdg8So3mV1eASEHxqSnp5lGa8R9Pyxz3iaZpBCBB
vDB7Fbbe5koVTmt+K06o96ki1/4NbHGyRVL/x5fFiVuTVfmk+GZNakH5dXDq0fwv
JyVmUtGYAiMJWPni2hGpAsbyjzLix9UNX5XiYIIrIr55IHtD5u1XNkmYLOdVQ98r
6hez3t2eaE0pP2k+mjRach+2tD93PBZmreHgVZtejumi+ZWLMqpd++AY0AzH0m8E
6sa8JFUAiYZbVtmrcGTCUCkzC2Es1/knSeZ41xki1qD0V3uw/APP8Q+BgbX3SJp0
EQIBAw==
-----END PUBLIC KEY-----

I want to find out what the modulo N and exponent E are from this key, in python?

Using pycrypto package I am able to load to the key as such:

from Crypto.PublicKey import RSA

# read the public key in:
public_key = RSA.importKey(open('key.pub', 'r').read())

but following the documentation of pycrypto's rsa module It wasn't clear how to extract the smaller components. How do I do this?


Solution

  • After an hour or so of playing around and googling and not finding a solution here is the really simple solution. Which stems off of how python objects work.

    When looking at the documentation, notice how it talks about the [keydata][1]

    What this tells us that when we do

    pub_key = RSA.importKey()
    

    we are creating an RSAobject. this object has the variables

    ['n', 'e', 'd', 'p', 'q', 'u']
    

    So you simply have to do:

    print(pub_key.n)
    print(pub_key.e)
    

    and so on to access those variables from that object. [1]: https://www.dlitz.net/software/pycrypto/api/current/Crypto.PublicKey.RSA._RSAobj-class.html#keydata