python实现rsa加密解密_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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值