# ============================================================
# CR13 | Educational implementation and trace functions
# Copyright © 2026/2027 Dr. Mohammad Alja’afreh
# PSUT IoT Engineering Studio | Educational, synthetic inputs
# ============================================================
from functools import lru_cache

# 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]

# Use polynomial extended Euclid to find a multiplicative inverse.
def gi(a,m=0x11b):
    if not a: raise ValueError('Zero has no multiplicative inverse')
    r,s=m,a; t,u=0,1
    while s:
        q,v,_=pdiv(r,s); r,s=s,v; t,u=u,t^pmul(q,u)
    if r!=1: raise ValueError('Not invertible')
    return pdiv(t,m)[1]

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

# Wrap shifted bits around the fixed word width instead of discarding them.
def rot(x,k,w): return ((x<<k)|(x>>(w-k)))&((1<<w)-1)

def xor(a,b): return bytes(x^y for x,y in zip(a,b))

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

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

# Compute the public AES substitution from a field inverse and affine transform.
@lru_cache(maxsize=256)
def sb(a):
    v=gi(a) if a else 0
    return v^rot(v,1,8)^rot(v,2,8)^rot(v,3,8)^rot(v,4,8)^0x63

# Generate all round words using Nk-dependent transformations and Rcon.
def expand(key):
    nk=len(key)//4
    if len(key) not in (16,24,32): raise ValueError('AES key must be 16, 24 or 32 bytes')
    w=[key[i:i+4] for i in range(0,len(key),4)]; trace=[]; rc=1
    for i in range(nk,4*(nk+7)):
        t=w[-1]; operation='XOR previous word'
        if i%nk==0:
            t=bytes(sb(x) for x in t[1:]+t[:1]); t=xor(t,bytes([rc,0,0,0])); operation=f'RotWord, SubWord, Rcon={hx(rc)}'; rc=gm(rc,2)
        elif nk==8 and i%nk==4: t=bytes(sb(x) for x in t); operation='SubWord'
        w.append(xor(w[i-nk],t)); trace.append(row(f'w[{i}]',operation=operation,base=hexs(w[i-nk]),temp=hexs(t),word=hexs(w[i])))
    return [b''.join(w[i:i+4]) for i in range(0,len(w),4)],trace

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['plaintext'],16);k=b(p['key']);keys,_=expand(k); after=xor(s,keys[0]);return pack({'rounds':len(keys)-1,'initial_xor':hexs(after)},[row('Column-major input',state=hexs(s)),row('Initial round key',state=hexs(keys[0])),row('AddRoundKey',state=hexs(after))])

PARAMS = {'plaintext': '00112233445566778899AABBCCDDEEFF', 'key': '000102030405060708090A0B0C0D0E0F'}
EXPECTED = {'rounds': 10, 'initial_xor': '00102030405060708090A0B0C0D0E0F0'}
ALT = {'plaintext': '00112233445566778899AABBCCDDEEFF', 'key': '000102030405060708090A0B0C0D0E0F1011121314151617'}
ALT_EXPECTED = {'rounds': 12, 'initial_xor': '00102030405060708090A0B0C0D0E0F0'}

if __name__ == "__main__":
    import argparse, json
    parser=argparse.ArgumentParser(description="CR13 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("CR13 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))
