/
challenge18.py
59 lines (43 loc) · 1.43 KB
/
challenge18.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
"""
Set 3: Implement CTR, the stream cipher mode
TODO: fix decryption bug
"""
from Crypto.Cipher import AES
import challenge2
import base64
import struct
class AES_CTR():
def __init__(self, key, nonce, blocksize, inc=True):
self._key = key
self._blocksize = blocksize
self._nonce = nonce
self._count = 0x0
self._cipher = AES.new(key, AES.MODE_ECB)
self._inc = inc
def encrypt(self, msg):
n = self._blocksize
count = self._count
ciphertext = b""
blocks = [msg[i:i+n] for i in range(0, len(msg), n)]
for b in blocks:
form = struct.pack("Q", self._nonce) + struct.pack("Q", count)
print("ALGORITHM", form)
keystream = self._cipher.encrypt(form)
if self._inc:
count += 1
if len(b) % n == 0:
ciphertext += challenge2.xor(keystream, b)
else:
end = len(b)
ciphertext += challenge2.xor(keystream[:end], b)
return ciphertext
def decrypt(self, msg):
return self.encrypt(msg)
def main():
unknown = b"L77na/nrFsKvynd6HzOoG7GHTLXsTVu9qvY/2syLXzhPweyyMTJULu/6/kXX0KSvoOLSFQ=="
raw = base64.b64decode(unknown)
cipher = AES_CTR(b"YELLOW SUBMARINE", 0x0, 16)
msg = cipher.decrypt(raw)
print("[*] Decrypted Ciphertext:\n{}".format(msg.decode('utf-8')))
if __name__ == '__main__':
main()