Python中的RSA加解密

新手上路,请多包涵

我需要帮助在 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 许可协议

阅读 305
1 个回答

为了使其工作,您需要在解密之前将密钥从 str 转换为元组(ast.literal_eval 函数)。这是固定代码:

 import Crypto
from Crypto.PublicKey import RSA
from Crypto import Random
import ast

random_generator = Random.new().read
key = RSA.generate(1024, random_generator) #generate pub and priv key

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')
f.write(str(encrypted)) #write ciphertext to file
f.close()

#decrypted code below

f = open('encryption.txt', 'r')
message = f.read()

decrypted = key.decrypt(ast.literal_eval(str(encrypted)))

print('decrypted', decrypted)

f = open ('encryption.txt', 'w')
f.write(str(message))
f.write(str(decrypted))
f.close()

原文由 Esdes 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏