-
Notifications
You must be signed in to change notification settings - Fork 2
/
m10.py
executable file
·51 lines (38 loc) · 1.27 KB
/
m10.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
#!/usr/bin/env python3
"""Implement CBC mode"""
from base64 import b64decode
from Crypto.Cipher import AES
from m02 import fixed_xor
from m09 import de_pkcs7
def encrypt_aes_cbc(key: bytes, iv: bytes, plaintext: bytes) -> bytes:
cypher = AES.new(key, AES.MODE_ECB)
blocks = [plaintext[i:i + len(key)]
for i in range(0, len(plaintext), len(key))]
vector = iv
cyphertext = b""
for block in blocks:
block = fixed_xor(block, vector)
block = cypher.encrypt(block)
cyphertext += block
vector = block
return cyphertext
def decrypt_aes_cbc(key: bytes, iv: bytes, cyphertext: bytes) -> bytes:
cypher = AES.new(key, AES.MODE_ECB)
blocks = [cyphertext[i:i + len(key)]
for i in range(0, len(cyphertext), len(key))]
vector = iv
plaintext = b""
for aesblock in blocks:
block = cypher.decrypt(aesblock)
plaintext += fixed_xor(block, vector)
vector = aesblock
return plaintext
def main() -> None:
with open("data/10.txt", "r") as data:
cyphertext = b64decode(data.read())
key = b"YELLOW SUBMARINE"
iv = bytes(len(key))
plaintext = de_pkcs7(decrypt_aes_cbc(key, iv, cyphertext))
print(plaintext.decode())
if __name__ == "__main__":
main()