我需要帮助在 Python 中使用 RSA 加密和解密。
我正在创建一个私钥/公钥对,用密钥加密消息并将消息写入文件。然后我从文件中读取密文并使用密钥解密文本。
我在解密部分遇到问题。正如您在下面的代码中看到的那样,当我输入 decrypted = key.decrypt(message)
时程序运行正常,但解密的消息再次加密。它似乎没有从文件中读取密文。
谁能帮我写这段代码,以便解密从文件中读取密文,然后使用密钥解密密文?
import Crypto
from Crypto.PublicKey import RSA
from Crypto import Random
random_generator = Random.new().read
key = RSA.generate(1024, random_generator) #generate public and private keys
publickey = key.publickey # pub key export for exchange
encrypted = publickey.encrypt('encrypt this message', 32)
#message to encrypt is in the above line 'encrypt this message'
print 'encrypted message:', encrypted #ciphertext
f = open ('encryption.txt', 'w'w)
f.write(str(encrypted)) #write ciphertext to file
f.close()
#decrypted code below
f = open ('encryption.txt', 'r')
message = f.read()
decrypted = key.decrypt(message)
print 'decrypted', decrypted
f = open ('encryption.txt', 'w')
f.write(str(message))
f.write(str(decrypted))
f.close()
原文由 user4866424 发布,翻译遵循 CC BY-SA 4.0 许可协议
为了使其工作,您需要在解密之前将密钥从 str 转换为元组(ast.literal_eval 函数)。这是固定代码: