首先,<_rsaobj n>,e,d,p,q,u,private>不是有效的键,不确定如何获取,但它是键的字符串表示形式,仅作为Python对象,不显示实际的键内容,还请注意,不能使用此字符串表示形式重新生成键对象。
在使用密钥进行RSA加密之前,您应该从诸如文件、在内存中生成等位置导入密钥
所以你应该做的是:key = RSA.importKey(externKey, passphrase=None)
其中externKey是一个字符串,因此您可以用这种方式从密钥文件加载密钥字符串。
或:key = RSA.generate(bits, randfunc=None, progress_func=None, e=65537)
其中bits是密钥的强度,例如2048。
无论哪种方式,您都将返回一个RSA密钥对象(_RSAobj),然后您可以像其他代码一样进行加密。
[编辑]完整代码import Crypto
from Crypto.PublicKey import RSA
#Quick way to generate a new key
private_key = RSA.generate(1024)
#Show the real content of the private part to console, be careful with this!
print(private_key.exportKey())
#Get the public part
public_key = private_key.publickey()
#Show the real content of the public part to console
print(public_key.exportKey())
#Save both keys into some file for future usage if needed
with open("rsa.pub", "w") as pub_file:
pub_file.write(public_key.exportKey())
with open("rsa.pvt", "w") as pvt_file:
pvt_file.write(private_key.exportKey())
#Load public key back from file and we only need public key for encryption
with open('rsa.pub', 'r') as pub_file:
pub_key = RSA.importKey(pub_file.read())
#Encrypt something with public key and print to console
encrypted = pub_key.encrypt('hello world', None) # the second param None here is useless
print(encrypted)
#Load private key back from file and we must need private key for decryption
with open('rsa.pvt', 'r') as pvt_file:
pvt_key = RSA.importKey(pvt_file.read())
#Decrypt the text back with private key and print to console
text = pvt_key.decrypt(encrypted)
print(text)