Getting Data在解密文件时必须以CBC模式填充到16字节边界

问题描述 投票:0回答:1

我正在尝试使用以下链接(python 加密代码)解密我加密的文件 解密文件时得到错误的幻数

但是当我尝试解密代码时出现以下错误:

ValueError: Data must be padded to 16 byte boundary in CBC mode
解密代码:

def decrypt_file(input_file_path, output_file_path, key):
    """
    Decrypt the given input file with the given key using AES and save the result to the given output file.
    """
    with open(input_file_path, "rb") as input_file:
        with open(output_file_path, "wb") as output_file:
            iv = input_file.read(AES.block_size)
            cipher = AES.new(key, AES.MODE_CBC, iv)
            while True:
                chunk = input_file.read(1024 * AES.block_size)
                if len(chunk) == 0:
                    break
                output_file.write(cipher.decrypt(chunk))

注意:使用 open ssl 解密使用以下命令工作正常

openssl aes-256-cbc -d -in sample.csv -out output_test.csv -K 30313233343536373839616263646566303132333435363453839616263646566 -iv 310401d79e639349639088859d7f433

现在我想在解密之前使用 python 解密,我们将加密文件分成 4 个块,并尝试使用上面的代码分别解密每个块,但我遇到了上述错误,请帮助我解决这个问题。

python encryption openssl aes
1个回答
0
投票

如错误所见。在 AES CDC 模式下,加密字节必须是 16 字节的倍数。

为了达到同样的效果,有一些方法具有内置机制,称为 pad 和 unpad,来自 Crypto.Util.Padding 包。

您的最终代码将如下所示: 加密端 -

padded_data = pad(data, AES.block_size)
encrypted_data = cipher.encrypt(padded_data)

解密方-

decrypted_data = cipher.decrypt(encrypted_data)
unpadded_data = unpad(decrypted_data, AES.block_size)

希望这有帮助。谢谢夏尔马。

© www.soinside.com 2019 - 2024. All rights reserved.