【问题标题】:How to find the right key when decryption is not decodable with PyCryptodome当使用 PyCryptodome 无法解码解密时如何找到正确的密钥
【发布时间】:2022-01-05 17:02:33
【问题描述】:

我是密码学的新手。有一个file.aes 使用 AES 和 128 位密钥和 ECB 进行加密。我不知道原始文件是什么格式。我得到了一组密钥,我被告知其中一个可以正确解密。所以我用 PyCryptodome 写了一个 python 脚本如下:

from Crypto.Cipher import AES

keys = [some 32 character keys]

file_in = open("file.aes", "rb")
ciphertext = file_in.read()

for key in keys:
    print (key)
    cipher = AES.new(str.encode(key), AES.MODE_ECB)
    data = cipher.decrypt(ciphertext)
    print(data)

对于所有密钥,解密会返回无法理解的字节数据,如下所示:

b'\xdd\xc1\xd4\x80\xd5\xe6\x92\xe7\xf3/\n\xa4\x90\x0b\x98(\x8a\xb8\xdf\xd1K\n\xeagW\xe9f\x80\xef9\x8e\xd5...'

我尝试使用ascii、utf-8、utf-16、utf-32 对其进行解码,希望看到明文,它们都返回UnicodeDecodeError:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xa7 in position 0: ordinal not in range(128)

如何为数据找到正确的编码?

我也开始怀疑原始文件是否也只是一个难以理解的二进制文件。单看无法识别,怎么知道哪个解密成功和正确?


编辑:

按照建议,我尝试加密和解密 utf-8 编码的纯文件,如下所示。解密没有问题。

from Crypto.Cipher import AES

key = b'ipu9TUv54yv]isFMh5@;t.5w34E2Ry@{'
cipher = AES.new(key, AES.MODE_ECB)

file_in = open("file", "rb")
data = file_in.read()
length = 16 - (len(data) % 16)
data += bytes([length]) * length

ciphertext = cipher.encrypt(data)
print(ciphertext)

plaintext = cipher.decrypt(ciphertext)
print(plaintext.decode())

更新:新的想法。由于我正在测试一堆大部分无效的密钥,因此解密数据可解码并返回错误可能是正常的。我应该使用 try 和 except。我还应该尝试documentation中列出的所有python编解码器。

from Crypto.Cipher import AES

keys = [some 32 character keys]
codecs = [all codecs]

file_in = open("file.aes", "rb")
ciphertext = file_in.read()

for key in keys:
    print (key)
    cipher = AES.new(str.encode(key), AES.MODE_ECB)
    data = cipher.decrypt(ciphertext)
    for codec in codecs:
        try :
            print(data.decode(codec))
        except:
            pass

在 print 语句中添加 decode 和 try-except 后,尝试所有编码后,我发现没有一个键可以打印任何内容。

【问题讨论】:

  • 如果不能确认解密数据是否正确,就无法知道解密是否成功。您是否尝试过使用您的代码加密已知文件以确保它能够解密?
  • @balmy 我刚试过。在编辑中更新。

标签: python encryption encoding pycryptodome


【解决方案1】:

我找到了一种使用 OpenSSL 成功解密它的方法。

编写一个脚本,使用一组键调用 OpenSSL,python bash 或 bat 无关紧要。无论密钥是对还是错,它都会创建一个输出文件,该文件可以被覆盖,但我们不在乎。如果密钥错误,它会打印错误的解密错误并以代码 1 退出。找到它不打印任何内容的密钥或以代码 0 退出。然后将密钥单独解密。就我而言,我找到了 8 个键,但其中只有一个是可读的。

这是这个想法的python实现:

keys = [a list of all possible keys]

for key in keys:
    # out.txt will be repeatedly overwritten
    command = "openssl enc -d -aes-128-ecb -in file.aes -out out.txt -K " + key
    output = os.system(command)
    # If OpenSSL exited with code 0
    if (output == 0):
        # Generates a separate file for that key
        command = "openssl enc -d -aes-128-ecb -in file.aes -out " + key + ".txt -K " + key
        output = os.system(command)

【讨论】:

    猜你喜欢
    • 2013-05-23
    • 1970-01-01
    • 2020-12-22
    • 2018-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多