Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
jvdsn
GitHub Repository: jvdsn/crypto-attacks
Path: blob/master/attacks/cbc/padding_oracle.py
2589 views
1
import logging
2
3
from Crypto.Util.strxor import strxor
4
5
6
def _attack_block(padding_oracle, iv, c):
7
logging.info(f"Attacking block {c.hex()}...")
8
r = bytes()
9
for i in reversed(range(16)):
10
s = bytes([16 - i] * (16 - i))
11
for b in range(256):
12
iv_ = bytes(i) + strxor(s, bytes([b]) + r)
13
if padding_oracle(iv_, c):
14
r = bytes([b]) + r
15
break
16
else:
17
raise ValueError(f"Unable to find decryption for {s}, {iv}, and {c}")
18
19
return strxor(iv, r)
20
21
22
def attack(padding_oracle, iv, c):
23
"""
24
Recovers the plaintext using the padding oracle attack.
25
:param padding_oracle: the padding oracle, returns True if the padding is correct, False otherwise
26
:param iv: the initialization vector
27
:param c: the ciphertext
28
:return: the (padded) plaintext
29
"""
30
p = _attack_block(padding_oracle, iv, c[0:16])
31
for i in range(16, len(c), 16):
32
p += _attack_block(padding_oracle, c[i - 16:i], c[i:i + 16])
33
34
return p
35
36