Skip to main content
 首页 » 编程设计

python之Pyocrypt DES3文件加密,解密缺失部分文本

2025年05月04日10leader

我正在使用此 blog 中的 3DES 加密(在标题 Applications 下)在 python 中带有 Crypto , 我一直在 Tree of Fun Files 上测试它,作为这个问题的例子 An Accountant and his Frog.txt在许多其他文件中(文件大小变化很大,例如 TOASTERS )。

加密

import os 
from Crypto.Cipher import DES3 
 
def encrypt_file(in_filename, out_filename, chunk_size, key, iv): 
    des3 = DES3.new(key, DES3.MODE_CFB, iv) 
    with open(in_filename, 'r') as in_file: 
        with open(out_filename, 'w') as out_file: 
            while True: 
                chunk = in_file.read(chunk_size) 
                if len(chunk) == 0: 
                    break 
                elif len(chunk) % 16 != 0: 
                    chunk += ' ' * (16 - len(chunk) % 16) 
                out_file.write(des3.encrypt(chunk)) 
 
def decrypt_file(in_filename, out_filename, chunk_size, key, iv): 
    des3 = DES3.new(key, DES3.MODE_CFB, iv) 
 
    with open(in_filename, 'r') as in_file: 
        with open(out_filename, 'w') as out_file: 
            while True: 
                chunk = in_file.read(chunk_size) 
                if len(chunk) == 0: 
                    break 
                out_file.write(des3.decrypt(chunk)) 

用法

import pyencrypt, md5 
from Crypto import Random 
iv = Random.get_random_bytes(8) 
m = md5.new() 
m.update("encryptionkey") 
key =  m.digest() 
.encrypt_file("C:\\treeoffunfiles\\Accountant and his frog.txt", 'C:\\treeoffun\\to_enc.enc', 8192, key, iv) 
pyencrypt.decrypt_file('C:\\treeoffunfiles\\to_enc.enc', 'C:\\treeoffunfiles\\to_enc.dec', 8192, key, iv) 

而且文件加密很棒(没有提示)!但是decryption文件的大小不是很好。这是一个 comparison原始文件和来自 notepad++ 的解密文件之间的输出.


(来源:iforce.co.nz)

关于解密文件为何缺少原始文件内容的任何想法?以及如何使解密(以及必要时的加密)更加准确(跨大小可能不同的文件)?

请您参考如下方法:

建议的答案由 DSM 发表在评论中(我一直在等他贴出答案,这个可以暂且保留)。

This works for me, but then I'm not on Windows. Could you open the files in binary mode ("rb"/"wb") instead and see if that helps? – DSM

问题是 3DES 加密的最初实现是在 unix 机器上运行的。而在 windows 系统上的结果不同。

为了修复丢失数据的 chunks,DSM 建议将文件输入/输出更改为二进制而不是常规读取/写入,这给出了所需的输出,如 here 所示。 .

fyi diffnow 仅存储 1 个月的结果。