Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
jvdsn
GitHub Repository: jvdsn/crypto-attacks
Path: blob/master/attacks/ecb/plaintext_recovery_hardest.py
2589 views
1
def attack(encrypt_oracle, unused_byte=0):
2
"""
3
Recovers a secret which is appended to a plaintext and encrypted using ECB.
4
In this scenario, the encryption oracle prepends a random prefix (length 0 to 16) to the plaintext.
5
:param encrypt_oracle: the encryption oracle
6
:param unused_byte: a byte that's never used in the secret or random prefix
7
:return: the secret
8
"""
9
paddings = [bytes([unused_byte] * i) for i in range(16)]
10
prefix = bytes([unused_byte] * 32)
11
secret = bytearray()
12
while True:
13
padding = paddings[15 - (len(secret) % 16)]
14
p = bytearray(prefix + padding + secret + b"0" + padding)
15
byte_index = len(prefix) + len(padding) + len(secret)
16
end1 = len(prefix) + len(padding) + len(secret) + 1
17
end2 = end1 + len(padding) + len(secret) + 1
18
for i in range(256):
19
p[byte_index] = i
20
c = encrypt_oracle(p)
21
while c[0:16] != c[16:32]:
22
c = encrypt_oracle(p)
23
24
if c[end1 - 16:end1] == c[end2 - 16:end2]:
25
secret.append(i)
26
break
27
else:
28
secret.pop()
29
break
30
31
return bytes(secret)
32
33