PyCrypto AES解密怪异 - python 2.7

时间:2015-12-23 20:51:03

标签: python python-2.7 encryption aes pkcs#7

我正在使用PyCrypto使用AES加密文件,但是当我解密它们时,它们在文件的头部有垃圾字符。这是一个剥离的示例,它加密Moby Dick的文本文件,然后尝试解密它:

from Crypto.Cipher import AES
from os import urandom

key = urandom(32)
iv = urandom(16)
aes = AES.new(key, AES.MODE_CBC, iv)

def encrypt_data(chunk):
    padding = AES.block_size
    if len(chunk):
        padding = AES.block_size - (len(chunk) % AES.block_size)
    return aes.encrypt(chunk + chr(padding)*padding)

with open('melville-moby-106.txt', 'r') as infile:
    with open('/tmp/test.tmp', 'w') as outfile:
        chunk = infile.read()
        while chunk:
            outfile.write(encrypt_data(chunk))
            chunk = infile.read()


with open('/tmp/test.tmp', 'r') as infile:
    with open('melville-moby-106.txt.new', 'w') as outfile:
        chunk = infile.read()
        while chunk:
            data = aes.decrypt(chunk)
            data = data[0:-ord(data[-1])]
            outfile.write(data)
            chunk = infile.read()

运行脚本后,我有这些文件:

-rw-rw-r--  1 brian  brian  1223687 Dec 23 15:11 melville-moby-106.txt
-rw-rw-r--  1 brian  brian  1223687 Dec 23 15:40 melville-moby-106.txt.new
-rw-rw-r--  1 brian  brian  1223696 Dec 23 15:40 test.tmp

大小看起来正确,但校验和不匹配:

96e829710ef8966d6eaef34b439cae6b  melville-moby-106.txt
94b94e495d449dad919083029a66b675  melville-moby-106.txt.new

如果我查看文件,这就是我看到的内容:

$ head -n 1 melville-moby-106.txt
c                                      1851

$ head -n 1 melville-moby-106.txt.new 
Z�x#8i���[��`j�6                       1851

文件内容的其余部分看起来没问题。

有人能告诉我我做错了吗?

由于

0 个答案:

没有答案