-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest.py
More file actions
72 lines (54 loc) · 1.99 KB
/
test.py
File metadata and controls
72 lines (54 loc) · 1.99 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
from Crypto.Cipher import AES
from Crypto import Random
from Crypto.Util.Padding import pad, unpad
from typing import Tuple, Optional
from solve import PaddingOracleSolver
BLOCK_SIZE = AES.block_size
key = Random.get_random_bytes(BLOCK_SIZE)
def encrypt(msg: bytes) -> Tuple[bytes, bytes]:
"""
Encrypts a given message using AES in CBC mode with random IV.
Args:
msg (bytes): The plaintext message to encrypt.
Returns:
Tuple[bytes, bytes]: A tuple containing the IV and the ciphertext.
"""
iv = Random.get_random_bytes(BLOCK_SIZE)
cipher = AES.new(key, AES.MODE_CBC, iv)
ct = cipher.encrypt(pad(msg, BLOCK_SIZE))
return iv, ct
def decrypt(iv: bytes, ct: bytes) -> Optional[bytes]:
"""
Decrypts a ciphertext using AES in CBC mode and verifies the padding.
Args:
iv (bytes): The initialization vector used during encryption.
ct (bytes): The ciphertext to decrypt.
Returns:
Optional[bytes]: The decrypted plaintext message, or None if padding is invalid.
"""
cipher = AES.new(key, AES.MODE_CBC, iv)
pt = cipher.decrypt(ct)
try:
return unpad(pt, BLOCK_SIZE)
except ValueError:
return None
def oracle(iv: bytes, ct: bytes) -> bool:
"""
Padding Oracle function that checks if a ciphertext can be decrypted correctly.
Args:
iv (bytes): The initialization vector used during encryption.
ct (bytes): The ciphertext to check.
Returns:
bool: True if the ciphertext can be decrypted correctly (valid padding), False otherwise.
"""
return decrypt(iv, ct) is not None
solver = PaddingOracleSolver(oracle)
message = Random.get_random_bytes(32)
print(f'message: {message.hex()}')
iv, ciphertext = encrypt(message)
print(f'iv: {iv.hex()}')
print(f'ciphertext: {ciphertext.hex()}')
plaintext = unpad(solver.solve(iv, ciphertext), BLOCK_SIZE)
print(f'plaintext: {plaintext.hex()}')
assert plaintext == message
print('[+] Success')