简体   繁体   中英

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

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM