Random ECB [Crypto]

Random ECB

Random ECB

We are provided server.py and a server:

  • URL: nc crypto.utctf.live 9003
  • File: server.py


Server prepends the plaintext with a 50% chance of 'A', followed by the chosen plaintext and then the flag. After encrypting it, it returns the ciphertext. It uses AES in ECB mode, so it's therefore vulnerable to a Chosen Plaintext Attack.


import pwn
import string

conn = pwn.remote('crypto.utctf.live', 9003)
conn.recvuntil(b'Input a string to encrypt (input \'q\' to quit):\n')

def sr(msg):
    conn.send(msg + b'\n')
    conn.recvuntil(b'Here is your encrypted string, have a nice day :)\n')
    res = conn.recv().split(b'\n')[0]
    res = bytes.fromhex(res.decode())
    return res

def srb(msg):
    m1, m2 = sr(msg), sr(msg)
    while m1 == m2:
        m2 = sr(msg)
    smsg = bytearray(b'A') + msg
    sm = sr(smsg)
    while sm != m1 and sm != m2:
        sm = sr(smsg)
    if sm == m1:
        return m2
    return m1

text = ""
plain = [ord(c) for c in text]
for block in range(1, 3):
    for i in range(15, -1, -1):
        p = bytearray(i * b'A')
        res = srb(p)
        b = res[block * 16 - 1]
        print(f'Byte {i}, looking for {b}')
        for c in string.printable:
            print(f'Checking {c}')
            ib = ord(c)
            res = srb(p + bytearray(plain) + bytearray([ib]))
            if res[block * 16 - 1] == b:
                text += c
print(f'Flag is: [{text}]')