# ============================================================
# CR05 | Educational implementation and trace functions
# Copyright © 2026/2027 Dr. Mohammad Alja’afreh
# PSUT IoT Engineering Studio | Educational, synthetic inputs
# ============================================================
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 row(label,**values): return {'step':label,**values}

# Standard DES lookup table: PC1
PC1=[57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4]

# Standard DES lookup table: PC2
PC2=[14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32]

# Select bits by the standard one-based DES position table.
def perm(x,width,table):
    v=0
    for i in table: v=(v<<1)|((x>>(width-i))&1)
    return v

# Discard parity with PC-1, rotate C/D, select 48-bit subkeys with PC-2.
def deskeys(key):
    cd=perm(key,64,PC1); c,d=cd>>28,cd&0xfffffff; out=[]
    for i,n in enumerate([1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1]):
        c,d=rot(c,n,28),rot(d,n,28); k=perm((c<<28)|d,56,PC2)
        out.append((c,d,k,n))
    return out

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):
    k=int.from_bytes(exact(p['key'],8),'big'); t=[row(f'Round {i+1}',C=hx(c,7),D=hx(d,7),rotation=s,K=hx(v,12)) for i,(c,d,v,s) in enumerate(deskeys(k))]
    return pack({'subkeys':len(t),'last':t[-1]['K']},t)

PARAMS = {'key': '133457799BBCDFF1'}
EXPECTED = {'subkeys': 16, 'last': 'CB3D8B0E17F5'}
ALT = {'key': '133457799BBCDFF0'}
ALT_EXPECTED = {'subkeys': 16, 'last': 'CB3D8B0E17F5'}

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