使用ImportKey从.PEM文件读取RSA密钥时的ValueError

时间:2017-01-15 05:53:13

标签: python encryption pycrypto

PyCrypto for RSA的文档 https://www.dlitz.net/software/pycrypto/api/current/Crypto.PublicKey.RSA-module.html提到了我们应该如何写入和读取密钥.PEM:

from Crypto.PublicKey import RSA

key = RSA.generate(2048)
f = open('mykey.pem','w')
f.write(RSA.exportKey('PEM'))
f.close()
...
f = open('mykey.pem','r')
key = RSA.importKey(f.read())

这就是我做到的。

random_generator = Random.new().read
rsakey = RSA.generate(1024, random_generator)
f = open(email + '.pem', 'w')
cipher = PKCS1_OAEP.new(rsakey.publickey())
f.write(str(rsakey.exportKey("PEM")))
f.write(str(rsakey.publickey().exportKey("PEM")))
...
f = open(receiver + '.pem', 'r')
key = RSA.importKey(f.read())
pubkey = key.publickey()
f.close()

但它会返回此错误:

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Crypto/PublicKey/RSA.py", line 682, in importKey
    raise ValueError("RSA key format is not supported")
ValueError: RSA key format is not supported

1 个答案:

答案 0 :(得分:1)

以“wb”模式写入密钥解决了问题

random_generator = Random.new().read
rsakey = RSA.generate(1024, random_generator)
f = open(email + '.pem', 'wb')
cipher = PKCS1_OAEP.new(rsakey.publickey())
f.write(str(rsakey.exportKey("PEM")))
f.write(str(rsakey.publickey().exportKey("PEM")))
...
f = open(receiver + '.pem', 'r')
key = RSA.importKey(f.read())
pubkey = key.publickey()
f.close()