如何在Python中解密OpenSSL AES加密文件?

Thi*_*ien 52 python encryption openssl aes pycrypto

OpenSSL为AES加密提供了一种流行的(但不安全 - 见下文!)命令行界面:

openssl aes-256-cbc -salt -in filename -out filename.enc
Run Code Online (Sandbox Code Playgroud)

Python以PyCrypto包的形式支持AES,但它只提供工具.如何使用Python/PyCrypto解密使用OpenSSL加密的文件?

注意

此问题过去也涉及使用相同方案的Python加密.我已经删除了那部分以阻止任何人使用它.不要以这种方式加密任何数据,因为它不符合今天的标准.你应该只使用解密,除了后向兼容性之外没有其他原因,即当你别无选择时.想要加密?如果可能的话,使用NaCl/libsodium.

Thi*_*ien 88

鉴于Python的普及,起初我很失望,没有完整的答案可以找到这个问题.我花了相当多的时间在这个板上阅读不同的答案,以及其他资源,以使其正确.我想我可能会分享结果以供将来参考,或许可以复习; 我绝不是加密专家!但是,下面的代码似乎无缝地工作:

from hashlib import md5
from Crypto.Cipher import AES
from Crypto import Random

def derive_key_and_iv(password, salt, key_length, iv_length):
    d = d_i = ''
    while len(d) < key_length + iv_length:
        d_i = md5(d_i + password + salt).digest()
        d += d_i
    return d[:key_length], d[key_length:key_length+iv_length]

def decrypt(in_file, out_file, password, key_length=32):
    bs = AES.block_size
    salt = in_file.read(bs)[len('Salted__'):]
    key, iv = derive_key_and_iv(password, salt, key_length, bs)
    cipher = AES.new(key, AES.MODE_CBC, iv)
    next_chunk = ''
    finished = False
    while not finished:
        chunk, next_chunk = next_chunk, cipher.decrypt(in_file.read(1024 * bs))
        if len(next_chunk) == 0:
            padding_length = ord(chunk[-1])
            chunk = chunk[:-padding_length]
            finished = True
        out_file.write(chunk)
Run Code Online (Sandbox Code Playgroud)

用法:

with open(in_filename, 'rb') as in_file, open(out_filename, 'wb') as out_file:
    decrypt(in_file, out_file, password)
Run Code Online (Sandbox Code Playgroud)

如果您认为有机会对此进行改进或将其扩展为更灵活(例如,使其无盐工作,或提供Python 3兼容性),请随意这样做.

注意

这个答案过去也涉及使用相同方案的Python加密.我已经删除了那部分以阻止任何人使用它.不要以这种方式加密任何数据,因为它不符合今天的标准.你应该只使用解密,除了后向兼容性之外没有其他原因,即当你别无选择时.想要加密?如果可能的话,使用NaCl/libsodium.

  • @rattray的主要区别是您的示例与其他有关Python在AES中的一般用法的示例一样。我的全部是关于与OpenSSL实现的兼容性,因此您可以使用众所周知的命令行工具来解密使用上述Python代码加密的文件,反之亦然。 (2认同)

Gre*_*gor 21

我正在重新发布您的代码并进行了一些更正(我不想模糊您的版本).当您的代码有效时,它不会检测填充周围的一些错误.特别是,如果提供的解密密钥不正确,您的填充逻辑可能会做一些奇怪的事情.如果您同意我的更改,您可以更新您的解决方案.

from hashlib import md5
from Crypto.Cipher import AES
from Crypto import Random

def derive_key_and_iv(password, salt, key_length, iv_length):
    d = d_i = ''
    while len(d) < key_length + iv_length:
        d_i = md5(d_i + password + salt).digest()
        d += d_i
    return d[:key_length], d[key_length:key_length+iv_length]

# This encryption mode is no longer secure by today's standards.
# See note in original question above.
def obsolete_encrypt(in_file, out_file, password, key_length=32):
    bs = AES.block_size
    salt = Random.new().read(bs - len('Salted__'))
    key, iv = derive_key_and_iv(password, salt, key_length, bs)
    cipher = AES.new(key, AES.MODE_CBC, iv)
    out_file.write('Salted__' + salt)
    finished = False
    while not finished:
        chunk = in_file.read(1024 * bs)
        if len(chunk) == 0 or len(chunk) % bs != 0:
            padding_length = bs - (len(chunk) % bs)
            chunk += padding_length * chr(padding_length)
            finished = True
        out_file.write(cipher.encrypt(chunk))

def decrypt(in_file, out_file, password, key_length=32):
    bs = AES.block_size
    salt = in_file.read(bs)[len('Salted__'):]
    key, iv = derive_key_and_iv(password, salt, key_length, bs)
    cipher = AES.new(key, AES.MODE_CBC, iv)
    next_chunk = ''
    finished = False
    while not finished:
        chunk, next_chunk = next_chunk, cipher.decrypt(in_file.read(1024 * bs))
        if len(next_chunk) == 0:
            padding_length = ord(chunk[-1])
            if padding_length < 1 or padding_length > bs:
               raise ValueError("bad decrypt pad (%d)" % padding_length)
            # all the pad-bytes must be the same
            if chunk[-padding_length:] != (padding_length * chr(padding_length)):
               # this is similar to the bad decrypt:evp_enc.c from openssl program
               raise ValueError("bad decrypt")
            chunk = chunk[:-padding_length]
            finished = True
        out_file.write(chunk)
Run Code Online (Sandbox Code Playgroud)

  • 请编辑我的帖子.无论如何,这是同行评审.一般来说,我同意一些错误检查是好的.虽然"丢失垫"有点误导,但实际上它太多了.这是OpenSSL给出的相同错误吗? (4认同)
  • 我从我的回答中删除了`encrypt`功能,并鼓励你这样做. (2认同)

小智 13

下面的代码应该是Python 3与代码中记录的小变化兼容.也想用os.urandom而不是Crypto.Random.'salted__'被salt_header取代,可以根据需要定制或留空.

from os import urandom
from hashlib import md5

from Crypto.Cipher import AES

def derive_key_and_iv(password, salt, key_length, iv_length):
    d = d_i = b''  # changed '' to b''
    while len(d) < key_length + iv_length:
        # changed password to str.encode(password)
        d_i = md5(d_i + str.encode(password) + salt).digest()
        d += d_i
    return d[:key_length], d[key_length:key_length+iv_length]

def encrypt(in_file, out_file, password, salt_header='', key_length=32):
    # added salt_header=''
    bs = AES.block_size
    # replaced Crypt.Random with os.urandom
    salt = urandom(bs - len(salt_header))
    key, iv = derive_key_and_iv(password, salt, key_length, bs)
    cipher = AES.new(key, AES.MODE_CBC, iv)
    # changed 'Salted__' to str.encode(salt_header)
    out_file.write(str.encode(salt_header) + salt)
    finished = False
    while not finished:
        chunk = in_file.read(1024 * bs) 
        if len(chunk) == 0 or len(chunk) % bs != 0:
            padding_length = (bs - len(chunk) % bs) or bs
            # changed right side to str.encode(...)
            chunk += str.encode(
                padding_length * chr(padding_length))
            finished = True
        out_file.write(cipher.encrypt(chunk))

def decrypt(in_file, out_file, password, salt_header='', key_length=32):
    # added salt_header=''
    bs = AES.block_size
    # changed 'Salted__' to salt_header
    salt = in_file.read(bs)[len(salt_header):]
    key, iv = derive_key_and_iv(password, salt, key_length, bs)
    cipher = AES.new(key, AES.MODE_CBC, iv)
    next_chunk = ''
    finished = False
    while not finished:
        chunk, next_chunk = next_chunk, cipher.decrypt(
            in_file.read(1024 * bs))
        if len(next_chunk) == 0:
            padding_length = chunk[-1]  # removed ord(...) as unnecessary
            chunk = chunk[:-padding_length]
            finished = True 
        out_file.write(bytes(x for x in chunk))  # changed chunk to bytes(...)
Run Code Online (Sandbox Code Playgroud)