【问题标题】:UnicodeDecodeError: 'utf-8' codec can't decode bytes in position 65534-65535: unexpected end of dataUnicodeDecodeError:“utf-8”编解码器无法解码位置 65534-65535 中的字节:数据意外结束
【发布时间】:2018-11-29 03:14:09
【问题描述】:

我想用简单的AES加密来加密文件,这是我的python3源代码。

import os, random, struct
from Crypto.Cipher import AES

def encrypt_file(key, in_filename, out_filename=None, chunksize=64*1024):
    if not out_filename:
        out_filename = in_filename + '.enc'
    iv = os.urandom(16)
    encryptor = AES.new(key, AES.MODE_CBC, iv)
    filesize = os.path.getsize(in_filename)
    with open(in_filename, 'rb') as infile:
        with open(out_filename, 'wb') as outfile:
            outfile.write(struct.pack('<Q', filesize))
            outfile.write(iv)
            while True:
                chunk = infile.read(chunksize)
                if len(chunk) == 0:
                    break
                elif len(chunk) % 16 != 0:
                    chunk += ' ' * (16 - len(chunk) % 16)
                outfile.write(encryptor.encrypt(chunk.decode('UTF-8','strict')))

它对某些文件工作正常,遇到一些文件的错误信息,如下所示:

encrypt_file("qwertyqwertyqwer",'/tmp/test1' , out_filename=None, chunksize=64*1024)

没有错误信息,工作正常。

encrypt_file("qwertyqwertyqwer",'/tmp/test2' , out_filename=None, chunksize=64*1024)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 17, in encrypt_file
UnicodeDecodeError: 'utf-8' codec can't decode bytes in position 65534-65535: unexpected end of data

如何修复我的 encrypt_file 函数?

按照t.m.adam 说的做,修复

outfile.write(encryptor.encrypt(chunk.decode('UTF-8','strict')))

作为

outfile.write(encryptor.encrypt(chunk))

尝试一些文件。

encrypt_file("qwertyqwertyqwer",'/tmp/test' , out_filename=None, chunksize=64*1024)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 16, in encrypt_file
TypeError: can't concat bytes to str

【问题讨论】:

  • 你为什么要解码你的数据? .encrypt() 可以处理字节,实际上在Python3中,如果你传递一个字符串,它会引发异常。
  • TypeError: can't concat bytes to str
  • 你能给我整个 python encrypt_file 函数吗?

标签: python python-3.x encryption


【解决方案1】:

您的代码的主要问题是您使用的是字符串。 AES 适用于二进制数据,如果您使用 PyCryptodome,此代码将引发 TypeError:

Object type <class 'str'> cannot be passed to C code

Pycrypto 接受字符串,但在内部将它们编码为字节,因此将字节解码为字符串是没有意义的,因为它将被编码回字节。此外,它使用 ASCII 编码(使用 PyCrypto v2.6.1、Python v2.7 测试)等等,例如此代码:

encryptor.encrypt(u'ψ' * 16)

会引发 UnicodeEncodeError:

File "C:\Python27\lib\site-packages\Crypto\Cipher\blockalgo.py", line 244, in encrypt
    return self._cipher.encrypt(plaintext)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-15

在加密或解密数据时应始终使用字节。然后你可以将明文解码为字符串,如果它是文本的话。

下一个问题是您的填充方法。它会生成一个字符串,因此当您尝试将其应用于应为字节的纯文本时,您会收到 TypeError。如果你用字节填充,你可以解决这个问题,

chunk += <b>b' '</b> * (16 - len(chunk) % 16)

但最好使用 PKCS7 填充(目前您使用的是零填充,但使用空格而不是零字节)。

PyCryptodome 提供填充功能,但您似乎正在使用 PyCrypto。在这种情况下,您可以实现 PKCS7 填充,或者更好地复制 PyCryptodome 的填充函数。

try:
    from Crypto.Util.Padding import pad, unpad
except ImportError:
    from Crypto.Util.py3compat import bchr, bord

    def pad(data_to_pad, block_size):
        padding_len = block_size-len(data_to_pad)%block_size
        padding = bchr(padding_len)*padding_len
        return data_to_pad + padding

    def unpad(padded_data, block_size):
        pdata_len = len(padded_data)
        if pdata_len % block_size:
            raise ValueError("Input data is not padded")
        padding_len = bord(padded_data[-1])
        if padding_len<1 or padding_len>min(block_size, pdata_len):
            raise ValueError("Padding is incorrect.")
        if padded_data[-padding_len:]!=bchr(padding_len)*padding_len:
            raise ValueError("PKCS#7 padding is incorrect.")
        return padded_data[:-padding_len]

pad 和 unpad 函数从 Crypto.Util.Padding 复制而来,并修改为仅使用 PKCS7 填充。请注意,当使用 PKCS7 填充时,填充最后一个块很重要,即使它的大小是块大小的倍数,否则您将无法正确取消填充。

将这些更改应用于encrypt_file 函数,

def encrypt_file(key, in_filename, out_filename=None, chunksize=64*1024):
    if not out_filename:
        out_filename = in_filename + '.enc'
    iv = os.urandom(16)
    encryptor = AES.new(key, AES.MODE_CBC, iv)
    filesize = os.path.getsize(in_filename)
    with open(in_filename, 'rb') as infile:
        with open(out_filename, 'wb') as outfile:
            outfile.write(struct.pack('<Q', filesize))
            outfile.write(iv)
            pos = 0
            while pos < filesize:
                chunk = infile.read(chunksize)
                pos += len(chunk)
                if pos == filesize:
                    chunk = pad(chunk, AES.block_size)
                outfile.write(encryptor.encrypt(chunk))

和匹配的decrypt_file函数,

def decrypt_file(key, in_filename, out_filename=None, chunksize=64*1024):
    if not out_filename:
        out_filename = in_filename + '.dec'
    with open(in_filename, 'rb') as infile:
        filesize = struct.unpack('<Q', infile.read(8))[0]
        iv = infile.read(16)
        encryptor = AES.new(key, AES.MODE_CBC, iv)
        with open(out_filename, 'wb') as outfile:
            encrypted_filesize = os.path.getsize(in_filename)
            pos = 8 + 16 # the filesize and IV.
            while pos < encrypted_filesize:
                chunk = infile.read(chunksize)
                pos += len(chunk)
                chunk = encryptor.decrypt(chunk)
                if pos == encrypted_filesize:
                    chunk = unpad(chunk, AES.block_size)
                outfile.write(chunk)

此代码与 Python2/Python3 兼容,它应该可以与 PyCryptodome 或 PyCrypto 一起使用。

但是,如果您使用的是 PyCrypto,我建议您更新到 PyCryptodome。 PyCryptodome 是 PyCrypto 的一个分支,它公开了相同的 API(因此您不必过多地更改代码),以及一些额外的功能:填充函数、经过身份验证的加密算法、KDF 等。另一方面,PyCrypto 不是不再维护,而且某些版本存在基于堆的缓冲区溢出漏洞:CVE-2013-7459。

【讨论】:

    【解决方案2】:

    除了公认的答案之外,我相信展示简单 AES 加密的多种实现可能对读者/新学习者有用:

    import os
    import sys
    import pickle
    import base64
    import hashlib
    import errno
    
    from Crypto import Random
    from Crypto.Cipher import AES
    
    DEFAULT_STORAGE_DIR = os.path.join(os.path.dirname(__file__), '.ncrypt')
    
    def create_dir(dir_name):
        """ Safely create a new directory. """
        try:
            os.makedirs(dir_name)
            return dir_name
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise OSError('Unable to create directory.')
    
    
    class AESCipher(object):
        DEFAULT_CIPHER_PICKLE_FNAME = "cipher.pkl"
    
        def __init__(self, key):
            self.bs = 32  # block size
            self.key = hashlib.sha256(key.encode()).digest()
    
        def encrypt(self, raw):
            raw = self._pad(raw)
            iv = Random.new().read(AES. block_size)
            cipher = AES.new(self.key, AES.MODE_CBC, iv)
            return base64.b64encode(iv + cipher.encrypt(raw))
    
        def decrypt(self, enc):
            enc = base64.b64decode(enc)
            iv = enc[:AES.block_size]
            cipher = AES.new(self.key, AES.MODE_CBC, iv)
            return self._unpad(cipher.decrypt(enc[AES.block_size:])).decode('utf-8')
    
        def _pad(self, s):
            return s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs)
    
        @staticmethod
        def _unpad(s):
            return s[:-ord(s[len(s)-1:])]
    

    并举例说明上述用法:

    while True:
        option = input('\n'.join(["="*80,
                                  "| Select an operation:",
                                  "| 1) E : Encrypt",
                                  "| 2) D : Decrypt",
                                  "| 3) H : Help",
                                  "| 4) G : Generate new cipher",
                                  "| 5) Q : Quit",
                                  "="*80,
                                  "> "])).lower()
        print()
    
        if option == 'e' or option == 1:
            plaintext = input('Enter plaintext to encrypt: ')
            print("Encrypted: {}".format(cipher.encrypt(plaintext).decode("utf-8")))
    
        elif option == 'd' or option == 2:
            ciphertext = input('Enter ciphertext to decrypt: ')
            print("Decrypted: {}".format(cipher.decrypt(ciphertext.encode("utf-8"))))
    
        elif option == 'h' or option == 3:
            print("Help:\n\tE: Encrypt plaintext\n\tD: Decrypt ciphertext.")
    
        elif option == 'g' or option == 4:
            if input("Are you sure? [yes/no]: ").lower() in ["yes", "y"]:
                cipher = AESCipher(key=input('Enter cipher password: '))
    
                with open(pickle_fname, 'wb') as f:
                    pickle.dump(cipher, f)
                print("Generated new cipher.")
    
        elif option == 'q' or option == 5:
            raise EOFError
        else:
            print("Unknown operation.")
    

    【讨论】:

    • +1,很好的课,但恐怕这个问题的标题不会吸引很多对Python加密感兴趣的读者。此外,这不适用于较大的文件,您必须像 OP 一样将它们“切割”成块。
    • 我点击了大多数与 Python 相关的特色问题,所以也许它吸引了一些人。 :D 为什么这不适用于较大的文件?
    • 是的,分块工作正常,只要块大小是块大小的倍数(仅适用于 CBC 和 ECB)。最后一个块可以是任意大小,将被填充。
    • 如果您需要一些提示,SHA256 不适合作为密钥派生函数,最好使用带有长随机盐(最少 8 个字节)和大量迭代的 hashlib.pbkdf2_hmac (至少 10,000 人)。此外,您可能希望对密文进行 HMAC,在某些情况下,CBC 可能容易受到填充预言机攻击。我编写了一个涵盖所有这些问题的 Python 类,如果需要,可以找到它here。目前它只使用基于密码的密钥,但我会尽快更新它。
    • 很高兴你喜欢它!几年前我开始了这个项目,当时我不得不将 Python 加密代码移植到 PHP。从那以后,我改进了实现并添加了更多的编程语言。最大的问题是 .NET,因为它的 KDF 选项有限,而且它不支持任何经过身份验证的加密算法,所以我不得不使用 Encrypt-then-MAC。随意批评/贡献。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-19
    • 2014-07-23
    • 2019-05-07
    • 1970-01-01
    • 2015-02-02
    • 1970-01-01
    相关资源
    最近更新 更多