Created
July 2, 2024 17:22
-
-
Save belkka/87fa85136349fa9af495974de53fb3ba to your computer and use it in GitHub Desktop.
AES CBC padding oracle in Python 3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
from Crypto.Cipher import AES | |
class PaddingOracle: | |
def __init__(self, key: bytes): | |
assert len(key) in AES.key_size | |
self.k = key | |
def encrypt(self, pt: bytes) -> bytes: | |
iv = os.urandom(AES.block_size) | |
cipher = AES.new(self.k, AES.MODE_CBC, iv) | |
pad = AES.block_size - len(pt) % AES.block_size | |
return iv + cipher.encrypt(pt + pad.to_bytes() * pad) | |
def has_valid_padding(self, ct: bytes) -> bool: | |
cipher = AES.new(self.k, AES.MODE_CBC) | |
padded_pt = cipher.decrypt(ct) | |
pad = padded_pt[-1] | |
return padded_pt.endswith(pad.to_bytes() * pad) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
padding is PKCS#7 [datatracker.ietf.org], i.e. one of
1
2 2
3 3 3
4 4 4 4
...
16 16 16 16 16 ... 16
Crypto.Cipher module provided by PyCryptodome
Hex-encoded key to initialize padding oracle (use
bytes.from_hex()
:d2ecd8e525321b2f282399662257ed6e
Hex-encoded messages to break using the padding oracle (do not decrypt them directly!):