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

标签 python encryption io des

我正在使用此 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++ 的解密文件之间的输出.

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 个月的结果。

关于python - Pyocrypt DES3文件加密,解密缺失部分文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14706384/

相关文章:

python - 无法运行Python脚本

asp.net - 我的 VIEWSTATE 是否加密?

c - openSSL:解密不会产生正确的纯文本

java - 在 Java 中将数组保存到文本文件

java - 在 Java 中一次性写入 SSL 套接字的最大数据限制是多少?

python - 如何将带分隔符的字符串拆分成一个集合?

python - 扭曲的 XmlStream : How to connect to events?

javascript - 如何在 Python 和 JavaScript 中对 "json"嵌套字典进行相同的哈希处理?

python - 将 Numpy 数组转换为稀疏字典的最快方法?

security - nginx auth_basic 是否发送明文密码?