这是我的代码:
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
Run Code Online (Sandbox Code Playgroud)
错误是“不支持 RSA 密钥格式”。任何人都可以帮助我从文件中写入/读取私钥的最佳方法吗?
小智 6
我的答案和一对钥匙有点复杂
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)
Run Code Online (Sandbox Code Playgroud)
您的代码存在多个问题,主要是您读取和写入密钥的方式。您永远不会关闭该文件,然后在读取功能期间将其打开两次;尝试将您的代码更改为:
#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())
Run Code Online (Sandbox Code Playgroud)
结果:
<_RSAobj @0x10d3cb2d8 n(4096),e,d,p,q,u,private>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27851 次 |
| 最近记录: |