Path: blob/master/Block-Cipher/Attack-ECB-Byte-at-a-Time/Challenges/Locked_Dungeon/enter_the_dungeon1.py
1402 views
#!/usr/bin/env python12import argparse3from hashlib import sha2564from Crypto.Cipher import AES5import os6import sys78BLOCK_SIZE = 169PAD_LIMIT = 4810KEY = os.urandom(16)1112pad_len = lambda inp: (BLOCK_SIZE - len(inp) % BLOCK_SIZE)13pad = lambda inp: inp + chr(pad_len(inp))*pad_len(inp)141516class AESCipher:17def __init__(self, key):18self.key = sha256(key).digest()1920def encrypt(self, raw):21cipher = AES.new(self.key, AES.MODE_ECB)22return "".join("{:02x}".format(ord(c)) for c in cipher.encrypt(raw))2324def mod_pad(self, inp, flag_size):25input_len = len(inp)26if input_len > PAD_LIMIT:27excess_len = input_len - PAD_LIMIT28if excess_len > flag_size:29padded_inp = inp[flag_size:flag_size + PAD_LIMIT]30else:31padded_inp = inp[:flag_size - excess_len] + inp[flag_size:]32return padded_inp33else:34padded_inp= pad(inp)35return padded_inp3637def mod_encrypt(self, raw, flag_size):38raw = self.mod_pad(raw, flag_size)39encrypted_data = self.encrypt(raw)40return encrypted_data4142if __name__ == "__main__":43with open("flag.txt") as fp:44flag = fp.read()45flag_size = len(flag)46if flag_size > PAD_LIMIT:47print("Flag is too big")48exit(1)49aescipher = AESCipher(key=KEY)50req_count = 051while req_count < 0x1900:52req_count += 153user_input = raw_input()54if len(user_input) > 0x64:55continue56sys.stdout.write(aescipher.mod_encrypt(flag + user_input, flag_size))57sys.stdout.write('\n')58sys.stdout.flush()5960