Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

rsa

Here is my code:

from Crypto.PublicKey import RSA

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

#Read key from file
file2 = open('keyfile.pem', 'rb')
key = RSA.importKey(file2.read()) #this is the problem

The error is "RSA key format is not supported." Can anyone help me with the best way to write/read the private key from a file?

like image 730
user6556957 Avatar asked May 22 '26 10:05

user6556957


1 Answers

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(b"dddddd",32)

print(x)
z = key1.decrypt(x)
print(z)
like image 80
Anagnostou John Avatar answered May 24 '26 01:05

Anagnostou John



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!