# ============================================================
# CR16 | Educational implementation and trace functions
# Copyright © 2026/2027 Dr. Mohammad Alja’afreh
# PSUT IoT Engineering Studio | Educational, synthetic inputs
# ============================================================
# Multiply binary polynomials by XORing shifted copies; no integer carries.
def pmul(a,b):
    r=0
    for i in range(b.bit_length()):
        if b>>i&1: r ^= a<<i
    return r

# Cancel the leading polynomial term repeatedly, retaining quotient and remainder.
def pdiv(a,b):
    if not b: raise ValueError('Zero polynomial divisor')
    q=0; steps=[]
    while a and a.bit_length()>=b.bit_length():
        k=a.bit_length()-b.bit_length(); old=a; q ^= 1<<k; a ^= b<<k
        steps.append((old,b<<k,a))
    return q,a,steps

# Reduce the carry-free product by the selected irreducible polynomial.
def gm(a,b,m=0x11b): return pdiv(pmul(a,b),m)[1]

def hx(n,w=2): return f'{n:0{w}X}'

def hexs(a): return bytes(a).hex().upper()

def row(label,**values): return {'step':label,**values}

# Multiply each column by the forward or inverse circulant matrix in GF(2^8).
def mix(s,inv=False):
    a=[14,11,13,9] if inv else [2,3,1,1]
    return bytes(gm(s[4*(i//4)+(i%4)%4],a[0])^gm(s[4*(i//4)+(i%4+1)%4],a[1])^gm(s[4*(i//4)+(i%4+2)%4],a[2])^gm(s[4*(i//4)+(i%4+3)%4],a[3]) for i in range(16))

def n(s): return int(s,0)

def b(s): return bytes.fromhex(s)

def exact(s,size):
    v=b(s)
    if len(v)!=size: raise ValueError(f'Expected {size} bytes')
    return v

def pack(result,trace): return {'result':result,'trace':trace}

EXTRA = {}

def run(p):
    s=exact(p['state'],16);o=mix(s);t=[row('Input matrix',state=hexs(s))]
    for c in range(4):
        for r in range(4):
            products=[gm(s[4*c+(r+j)%4],k) for j,k in enumerate([2,3,1,1])]; t.append(row(f'Column {c}, row {r}',products=[hx(x) for x in products],output=hx(o[4*c+r])))
    return pack({'output':hexs(o),'recovered':hexs(mix(o,True))},t+[row('Output matrix',state=hexs(o)),row('Inverse',state=hexs(mix(o,True)))])

PARAMS = {'state': 'DB135345000000000000000000000000'}
EXPECTED = {'output': '8E4DA1BC000000000000000000000000', 'recovered': 'DB135345000000000000000000000000'}
ALT = {'state': 'DA135345000000000000000000000000'}
ALT_EXPECTED = {'output': '8C4CA0BF000000000000000000000000', 'recovered': 'DA135345000000000000000000000000'}

if __name__ == "__main__":
    import argparse, json
    parser=argparse.ArgumentParser(description="CR16 synthetic cryptography exercise")
    parser.add_argument("--params", help="JSON parameter override file")
    parser.add_argument("--test", action="store_true")
    args=parser.parse_args()
    if args.test:
        assert run(PARAMS)["result"] == EXPECTED
        assert run(ALT)["result"] == ALT_EXPECTED
        print("CR16 default and changed input passed")
    else:
        parameters=PARAMS if not args.params else {**PARAMS,**json.load(open(args.params))}
        print(json.dumps(run(parameters),indent=2))
