from pwn import *

context.log_level = "info"

def decrypt_flag(enc_flag: bytes, a: int, b: int) -> bytes:
    a_inv = pow(a, -1, 2**64)
    out = bytearray()
    for i in range(0, len(enc_flag), 8):
        block = enc_flag[i : i + 8]
        if len(block) < 8:
            block = block.ljust(8, b"\x00")
        c = int.from_bytes(block, "little")
        p = ((c - b) * a_inv) % 2**64
        out += p.to_bytes(8, "little")
    return bytes(out)

with remote("192.168.0.221", 20054, timeout=5) as p:
    p.recvuntil(b"Encrypted flag (hex): ")
    enc_flag = bytes.fromhex(p.recvline().strip().decode())

    p.sendline(b"00" * 8)
    p.recvuntil(b"Ciphertext (hex): ")
    c1 = int.from_bytes(bytes.fromhex(p.recvline().strip().decode()), "little")
    b_val = c1

    p.sendline(b"01" + b"00" * 7)
    p.recvuntil(b"Ciphertext (hex): ")
    c2 = int.from_bytes(bytes.fromhex(p.recvline().strip().decode()), "little")
    a_val = (c2 - b_val)

    flag = decrypt_flag(enc_flag, a_val, b_val)
    print(flag.decode(errors="ignore"))
