-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathm18.py
executable file
·35 lines (25 loc) · 882 Bytes
/
m18.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
#!/usr/bin/env python3
"""Implement CTR, the stream cipher mode"""
# "Yo, VIP Let's kick it Ice, Ice, baby Ice, Ice, baby"
from struct import pack
from base64 import b64decode
from Crypto.Cipher import AES
from m02 import fixed_xor
def aes_ctr(cyphertext: bytes, key: bytes, nonce: int = 0) -> bytes:
c = [cyphertext[16 * i:16 * (i + 1)]
for i in range(0, len(cyphertext) // 16 + 1)]
cypher = AES.new(key, AES.MODE_ECB)
message = b""
ctr = 0
for block in c:
keystream = pack("<Qq", nonce, ctr)
message += fixed_xor(cypher.encrypt(keystream)[:len(block)], block)
ctr += 1
return message
def main() -> None:
with open("data/18.txt") as data_fd:
cyphertext = b64decode(data_fd.read().strip())
key = b"YELLOW SUBMARINE"
print(aes_ctr(cyphertext, key).decode())
if __name__ == "__main__":
main()