简体   繁体   English

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

[英]ValueError when reading RSA key from .PEM file using ImportKey

This documentation of PyCrypto for RSA https://www.dlitz.net/software/pycrypto/api/current/Crypto.PublicKey.RSA-module.html mentions this how we are supposed to write and read keys to and from .PEM : 用于RSA的PyCrypto的文档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())

and this is how i have done it. 这就是我做到的方式。

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()

but it returns this error: 但它返回此错误:

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

writing the keys in "wb" mode solved the problem 以“ 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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