Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ashutosh1206
GitHub Repository: ashutosh1206/crypton
Path: blob/master/Block-Cipher/Attack-ECB-Byte-at-a-Time/Challenges/Locked_Dungeon/enter_the_dungeon1.py
1402 views
1
#!/usr/bin/env python
2
3
import argparse
4
from hashlib import sha256
5
from Crypto.Cipher import AES
6
import os
7
import sys
8
9
BLOCK_SIZE = 16
10
PAD_LIMIT = 48
11
KEY = os.urandom(16)
12
13
pad_len = lambda inp: (BLOCK_SIZE - len(inp) % BLOCK_SIZE)
14
pad = lambda inp: inp + chr(pad_len(inp))*pad_len(inp)
15
16
17
class AESCipher:
18
def __init__(self, key):
19
self.key = sha256(key).digest()
20
21
def encrypt(self, raw):
22
cipher = AES.new(self.key, AES.MODE_ECB)
23
return "".join("{:02x}".format(ord(c)) for c in cipher.encrypt(raw))
24
25
def mod_pad(self, inp, flag_size):
26
input_len = len(inp)
27
if input_len > PAD_LIMIT:
28
excess_len = input_len - PAD_LIMIT
29
if excess_len > flag_size:
30
padded_inp = inp[flag_size:flag_size + PAD_LIMIT]
31
else:
32
padded_inp = inp[:flag_size - excess_len] + inp[flag_size:]
33
return padded_inp
34
else:
35
padded_inp= pad(inp)
36
return padded_inp
37
38
def mod_encrypt(self, raw, flag_size):
39
raw = self.mod_pad(raw, flag_size)
40
encrypted_data = self.encrypt(raw)
41
return encrypted_data
42
43
if __name__ == "__main__":
44
with open("flag.txt") as fp:
45
flag = fp.read()
46
flag_size = len(flag)
47
if flag_size > PAD_LIMIT:
48
print("Flag is too big")
49
exit(1)
50
aescipher = AESCipher(key=KEY)
51
req_count = 0
52
while req_count < 0x1900:
53
req_count += 1
54
user_input = raw_input()
55
if len(user_input) > 0x64:
56
continue
57
sys.stdout.write(aescipher.mod_encrypt(flag + user_input, flag_size))
58
sys.stdout.write('\n')
59
sys.stdout.flush()
60