import string
import random

import requests


HOST = 'zip-crypt.contest.qctf.ru'
TOKEN = 'HzQt8U0ytJ9MoDkJQSAG42BHBZFy1KzP4-PXlIYmQ0RNyTJ0Zr8SwNsPJvrrkev1'
BASE_URL = 'https://{}/{}/'.format(HOST, TOKEN)

ALPHABET = string.ascii_letters + string.digits + '_-}'
DEFAULT_TEXT_PREFIX = 'Long time no see! '
DEFAULT_FLAG_PREFIX = 'QCTF{'


def get_size(text):
    response = requests.post(BASE_URL + 'encrypt', data={'text': text})
    return len(response.content)


def pwn(text_prefix, flag_prefix, base_size):
    print(flag_prefix)
    if flag_prefix[-1] == '}':
        return flag_prefix

    possible_next_letters = [
        letter for letter in ALPHABET
        if get_size(text_prefix + flag_prefix + letter) == base_size]
    if not possible_next_letters:
        print('Could not guess the next letter')
        return None

    for letter in possible_next_letters:
        flag = pwn(text_prefix, flag_prefix + letter, base_size)
        if flag is not None:
            return flag
    return None


def pwn_block_cipher():
    base_size = get_size(DEFAULT_TEXT_PREFIX + DEFAULT_FLAG_PREFIX)
    padding = random.choice(ALPHABET)
    while base_size == get_size(padding + DEFAULT_TEXT_PREFIX + DEFAULT_FLAG_PREFIX):
        padding += random.choice(ALPHABET)
    return pwn(padding[:-1] + DEFAULT_TEXT_PREFIX, DEFAULT_FLAG_PREFIX, base_size)


if __name__ == '__main__':
    pwn_block_cipher()
