小编典典

如何读取PEM + PKCS#1格式的RSA公钥

python

我有PEM格式+ PKCS#1(我想)的RSA公钥:

-----BEGIN RSA PUBLIC KEY-----
MIGJAoGBAJNrHWRFgWLqgzSmLBq2G89exgi/Jk1NWhbFB9gHc9MLORmP3BOCJS9k
onzT/+Dk1hdZf00JGgZeuJGoXK9PX3CIKQKRQRHpi5e1vmOCrmHN5VMOxGO4d+zn
JDEbNHODZR4HzsSdpQ9SGMSx7raJJedEIbr0IP6DgnWgiA7R1mUdAgMBAAE=
-----END RSA PUBLIC KEY-----

我想在Python中获取其ASN1编码版本的SHA1摘要。第一步应该是读取此密钥,但是我在PyCrypto中无法做到这一点:

>> from Crypto.PublicKey import RSA
>> RSA.importKey(my_key)
ValueError: RSA key format is not supported

PyCrypto文档说支持PEM +
PKCS#1,所以我很困惑。我也尝试过M2Crypto,但事实证明M2Crypto不支持PKCS#1,而仅支持X.509。


阅读 215

收藏
2020-12-20

共1个答案

小编典典

PyCrypto支持 PKCS#1 ,因为它可以读取X.509SubjectPublicKeyInfo对象,该对象 包含PKCS#1
编码的RSA公钥。

而是,您密钥中编码的数据是纯RSAPublicKey对象(即具有两个INTEGER(模数和公用指数)的ASN.1 SEQUENCE)。

您仍然可以阅读它。尝试类似的方法:

from Crypto.PublicKey import RSA
from Crypto.Util import asn1
from base64 import b64decode

key64 = 'MIGJAoGBAJNrHWRFgWLqgzSmLBq2G89exgi/Jk1NWhbFB9gHc9MLORmP3BOCJS9k\
onzT/+Dk1hdZf00JGgZeuJGoXK9PX3CIKQKRQRHpi5e1vmOCrmHN5VMOxGO4d+znJDEbNHOD\
ZR4HzsSdpQ9SGMSx7raJJedEIbr0IP6DgnWgiA7R1mUdAgMBAAE='

keyDER = b64decode(key64)
seq = asn1.DerSequence()
seq.decode(keyDER)
keyPub = RSA.construct( (seq[0], seq[1]) )

从2.6版开始,PyCrypto还可以导入RsaPublicKeyASN.1对象。这样的代码就更简单了:

from Crypto.PublicKey import RSA
from base64 import b64decode

key64 = b'MIGJAoGBAJNrHWRFgWLqgzSmLBq2G89exgi/Jk1NWhbFB9gHc9MLORmP3BOCJS9k\
onzT/+Dk1hdZf00JGgZeuJGoXK9PX3CIKQKRQRHpi5e1vmOCrmHN5VMOxGO4d+znJDEbNHOD\
ZR4HzsSdpQ9SGMSx7raJJedEIbr0IP6DgnWgiA7R1mUdAgMBAAE='

keyDER = b64decode(key64)
keyPub = RSA.importKey(keyDER)
2020-12-20