#!/usr/bin/env python3

import subprocess
import string
import sys
import os
import struct

def xor(a, b):
    c = bytearray()
    for i in range(min(len(a), len(b))):
        c.append(a[i]^b[i])
    return bytes(c)

with open("cipher", "rb") as f:
    cipher = f.read()

def run_lych(inp):
    p = subprocess.Popen(["/tmp/lich", inp], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    so, se = p.communicate()
    return so.strip()

def try_inp(inp):
    return xor(inp.encode(), run_lych(inp))

def run_patch(i):
    with open("lich", "rb") as f:
        d = bytearray(f.read())
        d[0x7c5b:0x7c5f] = struct.pack("<I", i)
        with open("/tmp/lich", "wb") as f2:
            f2.write(d)

    return try_inp("a"*len(cipher))

print(run_patch(1997))

crib = xor(cipher[152:152+7], b"rgbctf{")
print(crib)

import time
s = time.time()
for seed in range(100000):
    if time.time() - s > 5:
        s = time.time()
        print(seed)
    res = run_patch(seed)
    if len(res) >= len(cipher) and res[152:152+7] == b"9289134":
        print(seed)
        print(xor(res, cipher))
