简体   繁体   中英

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 :

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

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

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