-
Notifications
You must be signed in to change notification settings - Fork 1
/
challenge15.py
85 lines (63 loc) · 2.54 KB
/
challenge15.py
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
73
74
75
76
77
78
79
80
81
82
83
84
85
def valid_padding(paddedMsg, block_size):
"""checks if `paddedMsg` has valid PKCS#7 padding for given `block_size`
Args:
paddedMsg (bytes): the padded text
block_size (int): the block size that is to be obtained by padding
Returns:
bool: True, if the padding is valid. False, otherwise.
"""
# if the length of the `paddedMsg` is not a multiple of `block_size`
if len(paddedMsg) % block_size != 0:
return False
last_byte = paddedMsg[-1]
# if the value of the last_byte is greater than or equal to block_size
if last_byte >= block_size:
return False
padValue = bytes([last_byte]) * last_byte
# if all the padding bytes are not the same
if paddedMsg[-last_byte:] != padValue:
return False
# if, after removing the padding, the remaining characters are not all printable
if not paddedMsg[:-last_byte].decode('ascii').isprintable():
return False
return True
def remove_padding(paddedMsg, block_size):
"""removes padding from `paddedMsg`, displays error-message if padding is invalid
Args:
paddedMsg (bytes): the message that is padded using PKCS#7 padding
block_size (int): the block size that is obtained by said padding
Raises:
ValueError: if the padding is invalid and then, shows an error message
"""
try:
if not valid_padding(paddedMsg, block_size):
raise ValueError
except ValueError:
print(f"{ paddedMsg } has invalid PKCS#7 padding.")
return
last_byte = paddedMsg[-1]
unpadded = paddedMsg[:-last_byte]
print(f"Padding removed successfully...")
print(f"Before padding removal: { paddedMsg }")
print(f"After padding removal: { unpadded }")
def test():
"""tests the `remove_padding()` function for various test cases.
"""
block_size = 16
# Test case 1: incorrect value < required:
paddedMsg = b'ICE ICE BABY\x03\x03\x03\x03'
remove_padding(paddedMsg, block_size)
# Test caes 2: incorrect value > required:
paddedMsg = b"ICE ICE BABY\x05\x05\x05\x05"
remove_padding(paddedMsg, block_size)
# Test case 3: incorrect length:
paddedMsg = b"ICE ICE BABY\x04\x04\x04"
remove_padding(paddedMsg, block_size)
# Test case 4: variable numbers:
paddedMsg = b"ICE ICE BABY\x01\x02\x03\x04"
remove_padding(paddedMsg, block_size)
# Test case 5: correct padding
paddedMsg = b"ICE ICE BABY\x04\x04\x04\x04"
remove_padding(paddedMsg, block_size)
if __name__ == "__main__":
test()