-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchallenge_09.py
More file actions
36 lines (27 loc) · 896 Bytes
/
challenge_09.py
File metadata and controls
36 lines (27 loc) · 896 Bytes
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
class PaddingError(Exception):
pass
def pkcs7(b: bytes, block_size: int = 16) -> bytes:
if block_size == 16:
pad_len = block_size - (len(b) & 15)
else:
pad_len = block_size - (len(b) % block_size)
return b + bytes([pad_len]) * pad_len
def strip_pkcs7(b: bytes) -> bytes:
n = b[-1]
if n == 0 or len(b) < n or not b.endswith(bytes([n])*n):
raise PaddingError
return b[:-n]
if __name__ == "__main__":
plaintext = b"YELLOW SUBMARINE"
padded = pkcs7(plaintext, block_size=20)
unpadded = strip_pkcs7(padded)
if padded != b"YELLOW SUBMARINE\x04\x04\x04\x04":
print("ERROR: pkcs7() returned", padded)
exit()
if unpadded != plaintext:
print("ERROR: strip_pkcs7() returned", unpadded)
exit()
print(f"{plaintext=}")
print(f"{padded=}")
print(f"{unpadded=}")
print("It worked!")