# ============================================================
# CR19 | 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

def invsub(a): return next(i for i in range(256) if sb(i)==a)

# Rotate each matrix row while preserving column-major state layout.
def shift(s,inv=False): return bytes(s[4*((i//4+(-1 if inv else 1)*(i%4))%4)+i%4] for i in range(16))

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

# 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

# Trace each reversible AES stage, omitting MixColumns in the final encryption round.
def aes(p,key,dec=False):
    if len(p)!=16: raise ValueError('Exactly 16-byte AES block')
    keys,_=expand(key); nr=len(keys)-1; s=p; trace=[row('Input',state=hexs(s))]
    def snap(r,name): trace.append(row(f'{r} {name}',state=hexs(s)))
    if not dec:
        s=xor(s,keys[0]); snap(0,'AddRoundKey')
        for r in range(1,nr+1):
            s=bytes(sb(x) for x in s); snap(r,'SubBytes'); s=shift(s); snap(r,'ShiftRows')
            if r<nr: s=mix(s); snap(r,'MixColumns')
            s=xor(s,keys[r]); snap(r,'AddRoundKey')
    else:
        s=xor(s,keys[nr]); snap(nr,'AddRoundKey')
        for r in range(nr-1,-1,-1):
            s=shift(s,True); snap(r,'InvShiftRows'); s=bytes(invsub(x) for x in s); snap(r,'InvSubBytes'); s=xor(s,keys[r]); snap(r,'AddRoundKey')
            if r: s=mix(s,True); snap(r,'InvMixColumns')
    return s,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']);c,t=aes(s,k);d,u=aes(c,k,True);return pack({'ciphertext':hexs(c),'recovered':hexs(d)},t+[dict(x,step='Decrypt '+x['step']) for x in u])

PARAMS = {'plaintext': '00112233445566778899AABBCCDDEEFF', 'key': '000102030405060708090A0B0C0D0E0F'}
EXPECTED = {'ciphertext': '69C4E0D86A7B0430D8CDB78070B4C55A', 'recovered': '00112233445566778899AABBCCDDEEFF'}
ALT = {'plaintext': '00112233445566778899AABBCCDDEEFF', 'key': '000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F'}
ALT_EXPECTED = {'ciphertext': '8EA2B7CA516745BFEAFC49904B496089', 'recovered': '00112233445566778899AABBCCDDEEFF'}

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