AES 解密实践之代码实现
AES 解密使用python脚本比较灵活,但是一定要保证脚本是调试过的,才能在找到正确的密文,密钥,初始向量的情况下,解出正确的明文。但是对于AES解密,命令行无法处理key截断的问题。
实际测试了一下,CBC模式,对于key截断的问题可以解决,但是CFB模式,目前还无法实验出可以解决key截断的问题。
1. CBC 模式代码展示
from Crypto.Cipher import AES
import base64
import binascii
import subprocess
iv_hex = "42b7c8d0fedcc3b550fd74600c846d60"
# 将 hex 转换为字节
iv = bytes.fromhex(iv_hex)
key_hex = "4b3652534f4739562b554a324f3157434942374a424544353851584d3854514c"
key = binascii.unhexlify(key_hex)
ciphertext_b64 = """qRARfftV7+r9rvtBRHlaW0o9QgNykFVhbI/alQHdZwfDHjDByAiZT59t2GmAvm/E
JGYuav4waz79J1M91Irdb/+iYGxu6ZnsfpXbvrSd6Ev32Z7Wn2uAmviCW43crWt3
UYktZZjvd+pJFHfu7nxxFCRv+OlEMNSCUzii7T/I6hFxI8E51X3unbBOiplPrKqp
evtnEENaCFcVAe/rDrKYQu4irkDQoBIeTCu4yODjIeEX9Ik6KDQCMvUiA2qKF2bG
az7Ept9xnpIsQslWeYGwvIJV3w1+4ZsFOi6rNsCxEoLx4dVq8r2OP5fFdklfL9c7
mnqQ0SAev1tgumG0tLX/pge7IghZKA8h6VZie74QXrTuDQ++w1nSVTO3YIH9zjx7
PWElAhVV/1TsjKZr6LpL2aou6tBxmQBiGo2BOYmuRFcuTGUK6pdS4qaYXbzM7vyp
g9/yjU9W+YBE+k3Wj7zJZDMVu0j0tWZqnmWkI/BFk5Rj/t/ikv/TbWnjtUw35VuC
t6bEv7i1zbzTWezV2OpRZaC7xRzenL8exn7TPJ5NC55ptww9+rp5q89Ltx+3n+YY
V+QkXZlTlBi1cl9LEwEJBVE68oGRcd32lhMdJHVIFhguG7ttFCTVw73MAbWNQRGU
+/4LLMzHFzPojC/B7MW2nQlXGd1GHhfTvv++4EODbKQu4wGTG2aI44EqPr8kJ/Pe
2amWCXsaG79E7FLV4isvVSVLNxdVjZ1tr++WwhuGI+KYOpDk+AxJ++B0MW3kgBXb
G5HoPBwbZmQtB570xPQ/di9HTfRzQohRW4PPn3tOKxZYQSnAkj+azihhsJJves7i
GnNiBORT1ML23x7b3URUs8nRkh+UTx3zYh4bxaOPTiN3GA8Z26vK2cBBsL3magj4
cbTAtR45H6LwwOGBImBVoYFEQlyoOfA301qdxdLAleI="""
# 解码 Base64 编码的密文
ciphertext = base64.b64decode(ciphertext_b64)
#print("Ciphertext (decoded):", ciphertext)
# 创建 AES-CFB 解密对象
cipher_decrypt = AES.new(key, AES.MODE_CBC, iv)
# 解密
decrypted = cipher_decrypt.decrypt(ciphertext)
# 打印解密结果
try:
print("解密结果:", decrypted.decode('utf-8'))
except UnicodeDecodeError as e:
print("Error decoding UTF-8:", e)
# 将密文保存到文件
with open("ciphertext.b64", "w") as f:
f.write(ciphertext_b64)
# 将密钥和 IV 保存到文件
with open("key.bin", "wb") as f:
f.write(key)
with open("iv.bin", "wb") as f:
f.write(iv)
# 使用 OpenSSL 命令行工具进行解密
subprocess.run([
"openssl", "enc", "-aes-256-cbc", "-d",
"-in", "ciphertext.b64",
"-out", "decryptedtest.bin",
"-base64",
"-K", key_hex,
"-iv", iv_hex
])
2. 结果
两种方式都能解出密文,但是命令行更靠谱一点,因为有可能出现key被截断后,代码可能无法成功解密的情况。
3. 解决方案
- 尽可能使用OpenSSL命令行处理。
4. 总结
- CBC 模式可能在某些情况下仍能产生可读输出,但这并不是安全的做法,避免截断密钥是最佳实践。