我需要在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()