【发布时间】:2015-07-15 09:51:34
【问题描述】:
我需要在 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()
【问题讨论】:
-
我在解密部分遇到问题 不能很好地描述您的问题。请阅读How to ask。你应该edit你的问题包括你的输入、输出和你的预期输出。
-
编辑有所帮助,但如果您包含程序的输出以及您期望的输出,它仍然会有所帮助
-
您的代码中有多个拼写错误。那么你实际尝试了什么?
-
请记住,这是"Textbook RSA",这是弱,尤其是对于短消息。填充(通过 PKCS#1)解决了 PyCrypto(和 PyCryptodome,维护的分支)可以解决的这些问题。
标签: python encryption rsa pycrypto