python rsa加密二进制文件_Python RSA文件加密解密结果因文件较大而不同

在使用Python的RSA加密大文件时,由于每次加密的字节数限制为128个,作者遇到加密解密结果不一致的问题。通过引入PKCS1_OAEP加密模式改进代码,解决了文件大小变化导致的加密解密稳定性问题。
摘要由CSDN通过智能技术生成

我知道RSA一次加密的字节数不能超过128个(模数),所以我把文件分块加密和解密。但是,如果我的文件大于几kb,每次运行程序时结果都会发生变化。有时整个文件被正确地加密和解密。有时只有前100行,等等。在这一点上,我想知道这是否是可靠性的问题加密.PublicKey.RSA模块。我的代码是:def encrypt(file, public_key):

read_size = 128

with open(file, 'rb') as original_file:

e_file = file + '.e'

with open(e_file, 'wb') as encrypted_file:

while True:

file_part = original_file.read(read_size)

if len(filePart) == 0:

break

encrypted_file.write(public_key.encrypt(file_part, None)[0])

os.remove(file)

def decrypt(file, private_key):

read_size = 128

with open(file, 'rb') as encrypted_file:

d_file = file[:-2]

with open(d_file, 'wb') as decrypted_file:

while True:

file_part = encrypted_file.read(read_size)

if len(filePart) == 0:

break

decrypted_file.write(private_key.decrypt(file_part))

os.remove(file)

private_key = RSA.generate(1024)

public_key = RSA.importKey(private_key.publickey().exportKey())

my_file = 'myfile.txt'

encrypt(my_file, public_key)

decrypt(my_file + '.e', private_key)

编辑:马丁的回答是有效的。这是我如何用他的答案解决问题的一个具体例子。

我使用了这个导入:

^{pr2}$

然后,我没有直接使用公钥进行加密,而是使用了以下方法:cipher = PKCS1_OAEP.new(publicKey)

encryptedFile.write(cipher.encrypt(filePart))

然后我做了类似的解密。在

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值