python中rsa解密_Python中的RSA加密和解密

I need help using RSA encryption and decryption in Python.

I am creating a private/public key pair, encrypting a message with keys and writing message to a file. Then I am reading ciphertext from file and decrypting text using key.

I am having trouble with the decryption portion. As you can see in my code below, when I put in decrypted = key.decrypt(message) that the program works, yet the decrypted message is encrypted again. It seems like it is not reading the ciphertext from the file.

Can anyone help me write this code so decryption reads ciphertext from file and then uses key to decrypt ciphertext?

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()

解决方案

In order to make it work you need to convert key from str to tuple before decryption(ast.literal_eval function). Here is fixed code:

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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值