gornvix
gornvix

Reputation: 3384

Load RSA public key file and convert to a binary array in Python?

I have a text file in PEM format for an RSA private key, for example:

-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEAhlxsnlo31l3u3w5jWyYpGVaNi9eDslPHgNV+I8Jb0hxGKXka
hnVOBu+b5IrcPcivWBIPQBNJp2svD/GVFWZQsKXshZA3meiRO+/k3qjBh7aDaakW
...etc
-----END RSA PRIVATE KEY-----

I load this in with the Python RSA library:

import rsa

with open('somefile.pem', mode='rb') as privatefile:
    keydata = privatefile.read()
privkey = rsa.PrivateKey.load_pkcs1(keydata)
print(type(privkey))
print(privkey)

This outputs five decimal numbers in brackets, like:

<class 'rsa.key.PrivateKey'>
PrivateKey(1234..., 7889..., etc)

How do I convert these numbers or class to a "binary array" (this is to pass the key to an API) ?

Update I'm guessing that "binary" is DER format?

Reference: https://stuvel.eu/python-rsa-doc/reference.html#classes

Upvotes: 2

Views: 2050

Answers (1)

larsks
larsks

Reputation: 312630

The text representation of an rsa.PrivateKey object is generating here, like this:

    def __repr__(self) -> str:
        return 'PrivateKey(%i, %i, %i, %i, %i)' % (self.n, self.e, self.d, self.p, self.q)

So if you want an array of those values, you can just write:

privkey = rsa.PrivateKey.load_pkcs1(keydata)
privkey_array = [privkey.n, privkey.e, privkey.d, privkey.p, privkey.q]

Upvotes: 2

Related Questions