我在 Python 中使用Crypto的这个博客(在标题Applications下)的 3DES 加密,我一直在有趣的文件树上测试它,作为这个问题的一个例子,An Accountant and his Frog.txt在许多其他文件(文件大小变化很大,例如TOASTERS)。
pyencrypt
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)
而且文件的加密很棒(没有抱怨)!但文件的解密不是那么好。这是原始文件和notepad++的解密文件之间的比较输出。
(来源:iforce.co.nz)
关于为什么解密文件缺少原始内容的任何想法?以及如何使解密(必要时加密)更准确(跨大小可能不同的文件)?