【发布时间】: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