1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
from Crypto.Cipher import AES
import base64
def remove_custom_padding(data):
"""
移除自定义填充:
1. 查找最后一个0x80字节
2. 验证之后的所有字节都是0x00
3. 返回去除填充的数据
"""
# 查找最后一个0x80的位置
last_80_pos = data.rfind(b'\x80')
if last_80_pos == -1:
raise ValueError("Invalid padding - no 0x80 byte found")
# 检查0x80之后的所有字节是否为0x00
for i in range(last_80_pos + 1, len(data)):
if data[i] != 0x00:
raise ValueError(f"Invalid padding - non-zero byte after 0x80 at position {i}")
return data[:last_80_pos]
def decrypt_aes_cbc(key, iv, ciphertext):
"""
AES-128-CBC解密并处理自定义填充
"""
cipher = AES.new(key, AES.MODE_CBC, iv)
decrypted = cipher.decrypt(ciphertext)
# 移除自定义填充
plaintext = remove_custom_padding(decrypted)
return plaintext
# 给定的Key和IV
key = bytes.fromhex("0123456789ABCDEF0123456789ABCDEF")
iv = bytes.fromhex("000102030405060708090A0B0C0D0E0F")
# 读取Base64编码的密文文件
with open("cipher.bin", "rb") as f:
ciphertext_b64 = f.read()
# 解码Base64得到二进制密文
ciphertext = base64.b64decode(ciphertext_b64)
# 解密
plaintext = decrypt_aes_cbc(key, iv, ciphertext)
# 输出解密结果
print("Decrypted plaintext (hex):", plaintext.hex())
print("Decrypted plaintext (str):", plaintext.decode('utf-8', errors='replace'))
|