Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 741
Konstantino Sparakis Avatar asked Feb 28 '17 08:02

Konstantino Sparakis


People also ask

What is modulus and exponent in RSA public key?

Public key contains modulus and public exponent. Modulus (n) is the product of two prime numbers used to generate the key pair. Public exponent (d) is the exponent used on signed / encoded data to decode the original value.

What is N in RSA public key?

The integer number n is called "modulus" and it defines the RSA key length. It is typically very large prime number (e.g. 2048 bits).

How do you find the public key from modulus and exponent?

To generate public key from the exponent and modulus, they need to be transformed to BigInteger, and then KeyFactory from Java security can be used.


2 Answers

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

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.

like image 137
Konstantino Sparakis Avatar answered Sep 20 '22 00:09

Konstantino Sparakis


For example if your public key is saved as alicepublic.pem in your directory:

>>>from Crypto.PublicKey import RSA
>>>f = open("alicepublic.pem", "r")
>>>key = RSA.importKey(f.read())
>>>print key.n #displays n
>>>print key.e #displays e

Doing this in the interpreter will display the components.

to install Crypto use this: pip install pycryptodome

like image 41
Sindre Trandum Avatar answered Sep 19 '22 00:09

Sindre Trandum