import socket
import base64
import threading
from Crypto.Cipher import AES

flag = 'HM{3cb_0r4cl3}'
key = '12345678abcdefgh'

BIND_IP = '192.168.0.12'
BIND_PORT = 8000

def pad(raw):

    if (len(raw) % 16 == 0):
        return raw
    padding_required = 16 - (len(raw) % 16)
    padChar = b'\x00'
    data = raw.encode('ascii') + padding_required * padChar
    return data

def handle_client(client_socket):
    client_socket.send(bytes('I will send you AES(<input>+flag):\n'.encode('ascii')))
    request = client_socket.recv(1024)
    string = request.decode('ascii').rstrip()
    cipher = AES.AESCipher(key, AES.MODE_ECB)
    ciphertext = base64.b64encode(cipher.encrypt(pad(string+flag)))
    client_socket.send(ciphertext)
    client_socket.close()

def tcp_server():
    server = socket.socket( socket.AF_INET, socket.SOCK_STREAM)
    server.bind(( BIND_IP, BIND_PORT))
    server.listen(5)
    print("[*] Listening on %s:%d" % (BIND_IP, BIND_PORT))

    while 1:
        client, addr = server.accept()
        print("[*] Accepted connection from: %s:%d" %(addr[0], addr[1]))
        client_handler = threading.Thread(target=handle_client, args=(client,))
        client_handler.start()

if __name__ == '__main__':
    tcp_server()
