python RSA key format is not supported when reading from .pem file

python RSA key format is not supported when reading from .pem file

You have multiple issues with your code, mainly the way you are reading and writing the key. You never close the file, then open it twice during your read function; try changing your code to:

#Write key to file
key = RSA.generate(4096)
f = open(keyfile.pem, wb)
f.write(key.exportKey(PEM))
f.close()

#Read key from file
f = open(keyfile.pem, rb)
key = RSA.importKey(f.read())

Result:

<_RSAobj @0x10d3cb2d8 n(4096),e,d,p,q,u,private>

My answer and a little more complicated with pair of keys

from Crypto.PublicKey import RSA
key = RSA.generate(4096)
f = open(/home/john/Desktop/my_rsa_public.pem, wb)
f.close()
f.write(key.publickey().exportKey(PEM))
f = open(/home/john/Desktop/my_rsa_private.pem, wb)
f.write(key.exportKey(PEM))
f.close()

f = open(/home/john/Desktop/my_rsa_public.pem, rb)
f1 = open(/home/john/Desktop/my_rsa_private.pem, rb)
key = RSA.importKey(f.read())
key1 = RSA.importKey(f1.read())

x = key.encrypt(bdddddd,32)

print(x)
z = key1.decrypt(x)
print(z)

python RSA key format is not supported when reading from .pem file

Leave a Reply

Your email address will not be published.