CBC字节翻转攻击

突然遇见了需要这个的,了解了一下,大概改了改一个古老的脚本,能用了

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
from base64 import b64encode
import base64
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
def cbc_bit_attack_mul(c, m, position, target):
"""
实现CBC模式下的位攻击算法 通过修改密文中的特定位来达到解密的目的。

参数:
- c: 密文 类型为bytes。
- m: 明文,类型为字符串。
- position: 需要修改的位的位置列表 索引从16开始计数。
- target: 目标位的值列表 与position列表元素一一对应 元素为字符。

返回值:
- 修改后的密文 类型为bytes。
"""
l = len(position)
r = bytearray.fromhex(c) # 初始化变量r为密文c的副本,并将其转换为字节串
for i in range(l):
change = position[i] # 计算在密文中需要修改的位置
tmp = chr(r[change] ^ ord(m[position[i]]) ^ ord(target[i]))
r[change] = ord(tmp)
return bytes(r)

m = '{"admin": 0, "username": "user1"}'
m=str(m) # 待加密的明文
print(m)
key = "1234567890abcdef" # 加密密钥
iv = "fedcba0987654321" # 初始向量
cipher = AES.new(key.encode(), AES.MODE_CBC, iv.encode())
#c = cipher.encrypt(m.encode()) # 加密明文,并打印加密后的密文的十六进制表示
c=b64encode(iv.encode() + cipher.encrypt(pad(m.encode(), AES.block_size)))
decoded_c = base64.b64decode(c)
c = decoded_c.hex()
print(c)
c_new = cbc_bit_attack_mul(c, m, [11 - 1], ['1']) # 使用位攻击算法修改密文
print(b64encode(c_new))
cipher = AES.new(key.encode(), AES.MODE_CBC, iv.encode()) # 创建AES解密对象
m = cipher.decrypt(c_new) # 解密修改后的密文,并打印解密结果
print(m)