Python和OpenSSL:无法解密

时间:2016-10-28 10:18:35

标签: python python-3.x encryption aes pyopenssl

我找到了一小段能够在AES(128位)CBC模式下加密(和解密)文件的代码。它甚至在解密时也能完美无缺,所以我相信OpenSSL能够(当然)能够解密我的文件,但它似乎是不可能的。我收到“错误读取输入文件

java.lang.IllegalStateException: Cannot call this method while RecyclerView is computing a layout or scrolling

错误始终如一:“读取输入文件时出错”。怎么可能?我使用的命令是:

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

def encrypt_file(key, in_filename, out_filename=None, chunksize=64*1024):
    """ Encrypts a file using AES (CBC mode) with the
        given key.

        key:
            16, 24 or 32 bytes long

        in_filename:
            Name of the input file

        out_filename:
            If None, '<in_filename>.enc' will be used.

        chunksize:
            Sets the size of the chunk which the function
            uses to read and encrypt the file.
            Chunksize must be divisible by 16.
        """
    if not out_filename:
            out_filename = in_filename + '.enc'

    iv = ''.join(chr(random.randint(0, 0xFF)) for i in range(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))

为什么不起作用?

1 个答案:

答案 0 :(得分:0)

OpenSSL使用自己的文件格式。特别是,有一个Salted__标题,以及用于导出IV的盐(即IV不直接与加密数据一起存储)。

您可以在https://scottlinux.com/2013/10/13/how-to-encrypt-a-file-with-openssl/https://crypto.stackexchange.com/questions/3298/is-there-a-standard-for-openssl-interoperable-aes-encryption中找到一些提示,但它们并不能描述实际的格式。

您可以检查OpenSSL代码来解决这个问题,但最重要的是OpenSSL使用自己的文件格式,如果您希望OpenSSL解密文件,则必须使用它。