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

# Generate sector tweaks and handle short final blocks using ciphertext stealing.
def xts(data,key,sector,dec=False):
    if len(data)<16 or len(key) not in (32,64): raise ValueError('XTS needs >=16 data bytes and 32 or 64 key bytes')
    k1,k2=key[:len(key)//2],key[len(key)//2:]
    if k1==k2: raise ValueError('Use distinct XTS keys')
    t=aes(sector.to_bytes(16,'little'),k2)[0]; out=b''; trace=[]
    def mulx(t):
        n=int.from_bytes(t,'little'); return (((n<<1)&((1<<128)-1))^(0x87 if n>>127 else 0)).to_bytes(16,'little')
    def xex(b,t,d): return xor(aes(xor(b,t),k1,d)[0],t)
    n,r=divmod(len(data),16)
    for i in range(n-(1 if r else 0)):
        b=data[16*i:16*i+16]; c=xex(b,t,dec); trace.append(row(f'Block {i}',tweak=hexs(t),input=hexs(b),output=hexs(c))); out+=c; t=mulx(t)
    if r:
        b=data[16*(n-1):16*n]; tail=data[16*n:]; tn=mulx(t)
        if not dec:
            cc=xex(b,t,False); partial=cc[:r]; full=xex(tail+cc[r:],tn,False)
        else:
            pp=xex(b,tn,True); partial=pp[:r]; full=xex(tail+pp[r:],t,True)
        out+=full+partial; trace.append(row('Ciphertext stealing',tweak=hexs(t),next_tweak=hexs(tn),full=hexs(full),partial=hexs(partial)))
    return out,trace

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

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

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

EXTRA = {}

def run(p):
    s=b(p['plaintext']);k=b(p['key']);sector=n(p['sector'])
    if not 0<=sector<=9007199254740991: raise ValueError('Sector must be a nonnegative safe integer')
    c,t=xts(s,k,sector);d,u=xts(c,k,sector,True);return pack({'ciphertext':hexs(c),'recovered':hexs(d),'length':len(c)},t+[dict(x,step='Decrypt '+x['step']) for x in u])

PARAMS = {'plaintext': '00112233445566778899AABBCCDDEEFF1122334455', 'key': '000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F', 'sector': '7'}
EXPECTED = {'ciphertext': '219BF750510C5D9F0DE3A9630D29B7FC96ABE5533D', 'recovered': '00112233445566778899AABBCCDDEEFF1122334455', 'length': 21}
ALT = {'plaintext': '00112233445566778899AABBCCDDEEFF1122334455', 'key': '000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F', 'sector': '8'}
ALT_EXPECTED = {'ciphertext': 'F2FE3C63A973D11C41DC328B0C3AACB95082C174BB', 'recovered': '00112233445566778899AABBCCDDEEFF1122334455', 'length': 21}

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