{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "69487855",
   "metadata": {},
   "source": [
    "# CR19 · AES · complete cipher and inverse\n",
    "\n",
    "\n",
    "Initial AddRoundKey; rounds SubBytes, ShiftRows, MixColumns, AddRoundKey; final omits MixColumns. Inverse begins with last round key, then inverse transformations and reversed keys. FIPS example 001122…EEFF with key 000102…0F gives 69C4…C55A.\n",
    "\n",
    "**Learning outcomes:** Explain the named transformation, calculate a baseline trace, reproduce it in the browser and Python, and interpret one controlled change.\n",
    "\n",
    "**Boundary:** Synthetic inputs and software computation only; no Raspberry Pi, broker or cloud service required. Educational code is not production cryptography."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "id": "concept019",
   "source": [
    "## Complete AES and inverse\n",
    "\n",
    "Encryption composes invertible nonlinear, permutation and linear layers with key XOR. Decryption applies inverse transformations in reverse order with matching round keys; equivalent inverse formulations may transform keys.\n",
    "\n",
    "**Mathematical / protocol foundations:** Initial XOR, Nr−1 full rounds, final round without MixColumns. Inverse starts with last round key, then InvShiftRows, InvSubBytes and reverse-order round operations. Known-answer tests check exact block/key mappings.\n",
    "\n",
    "**Worked teaching example and interpretation:** Standard AES-128 vector uses plaintext 00112233445566778899AABBCCDDEEFF and key 000102030405060708090A0B0C0D0E0F. Initial XOR=00102030405060708090A0B0C0D0E0F0; ciphertext=69C4E0D86A7B0430D8CDB78070B4C55A. Decryption must recover all 16 original bytes.\n",
    "\n",
    "Compare corresponding states; for randomized or timed runs compare invariants rather than literal random bytes or timings.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Mathematical foundations\n",
    "\n",
    "Encryption begins with AddRoundKey, then repeats SubBytes, ShiftRows, MixColumns and AddRoundKey. The last round omits MixColumns. Decryption starts with the final round key and reverses the operations: InvShiftRows, InvSubBytes, AddRoundKey, then InvMixColumns except at the end. Round states are column-major byte sequences. This is a raw single-block primitive, not an authenticated message-encryption system.\n",
    "\n",
    "**Worked calculation.** Known-answer vector: plaintext 00112233445566778899AABBCCDDEEFF with key 000102030405060708090A0B0C0D0E0F yields 69C4E0D86A7B0430D8CDB78070B4C55A.\n",
    "\n",
    "**Practical baseline.** Load the baseline. Inspect initial AddRoundKey and every round-1 transformation. Select byte 0 in each step to reproduce its calculation. Locate round 10, confirm no MixColumns, then follow inverse steps to plaintext recovery.\n",
    "\n",
    "**Controlled experiment.** Keep the plaintext fixed and use the 24- and 32-byte sequential keys. Verify ciphertexts DDA97CA4864CDFE06EAF70A0EC0D7191 and 8EA2B7CA516745BFEAFC49904B496089. Count forward AddRoundKey operations and record final round labels.\n",
    "\n",
    "**Evidence.** Key size, round count, initial XOR, round-1 state sequence, ciphertext, recovered plaintext, known-answer and library verification."
   ],
   "id": "41bcf74748278711"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ded8d915",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ============================================================\n",
    "# CR19 | Implement the mathematical operations\n",
    "# Copyright © 2026/2027 Dr. Mohammad Alja’afreh\n",
    "# PSUT IoT Engineering Studio | Educational, synthetic inputs\n",
    "# ============================================================\n",
    "from functools import lru_cache\n",
    "\n",
    "# Multiply binary polynomials by XORing shifted copies; no integer carries.\n",
    "def pmul(a,b):\n",
    "    r=0\n",
    "    for i in range(b.bit_length()):\n",
    "        if b>>i&1: r ^= a<<i\n",
    "    return r\n",
    "\n",
    "# Cancel the leading polynomial term repeatedly, retaining quotient and remainder.\n",
    "def pdiv(a,b):\n",
    "    if not b: raise ValueError('Zero polynomial divisor')\n",
    "    q=0; steps=[]\n",
    "    while a and a.bit_length()>=b.bit_length():\n",
    "        k=a.bit_length()-b.bit_length(); old=a; q ^= 1<<k; a ^= b<<k\n",
    "        steps.append((old,b<<k,a))\n",
    "    return q,a,steps\n",
    "\n",
    "# Reduce the carry-free product by the selected irreducible polynomial.\n",
    "def gm(a,b,m=0x11b): return pdiv(pmul(a,b),m)[1]\n",
    "\n",
    "# Use polynomial extended Euclid to find a multiplicative inverse.\n",
    "def gi(a,m=0x11b):\n",
    "    if not a: raise ValueError('Zero has no multiplicative inverse')\n",
    "    r,s=m,a; t,u=0,1\n",
    "    while s:\n",
    "        q,v,_=pdiv(r,s); r,s=s,v; t,u=u,t^pmul(q,u)\n",
    "    if r!=1: raise ValueError('Not invertible')\n",
    "    return pdiv(t,m)[1]\n",
    "\n",
    "def hx(n,w=2): return f'{n:0{w}X}'\n",
    "\n",
    "# Wrap shifted bits around the fixed word width instead of discarding them.\n",
    "def rot(x,k,w): return ((x<<k)|(x>>(w-k)))&((1<<w)-1)\n",
    "\n",
    "def xor(a,b): return bytes(x^y for x,y in zip(a,b))\n",
    "\n",
    "def hexs(a): return bytes(a).hex().upper()\n",
    "\n",
    "def row(label,**values): return {'step':label,**values}\n",
    "\n",
    "# Compute the public AES substitution from a field inverse and affine transform.\n",
    "@lru_cache(maxsize=256)\n",
    "def sb(a):\n",
    "    v=gi(a) if a else 0\n",
    "    return v^rot(v,1,8)^rot(v,2,8)^rot(v,3,8)^rot(v,4,8)^0x63\n",
    "\n",
    "def invsub(a): return next(i for i in range(256) if sb(i)==a)\n",
    "\n",
    "# Rotate each matrix row while preserving column-major state layout.\n",
    "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))\n",
    "\n",
    "# Multiply each column by the forward or inverse circulant matrix in GF(2^8).\n",
    "def mix(s,inv=False):\n",
    "    a=[14,11,13,9] if inv else [2,3,1,1]\n",
    "    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))\n",
    "\n",
    "# Generate all round words using Nk-dependent transformations and Rcon.\n",
    "def expand(key):\n",
    "    nk=len(key)//4\n",
    "    if len(key) not in (16,24,32): raise ValueError('AES key must be 16, 24 or 32 bytes')\n",
    "    w=[key[i:i+4] for i in range(0,len(key),4)]; trace=[]; rc=1\n",
    "    for i in range(nk,4*(nk+7)):\n",
    "        t=w[-1]; operation='XOR previous word'\n",
    "        if i%nk==0:\n",
    "            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)\n",
    "        elif nk==8 and i%nk==4: t=bytes(sb(x) for x in t); operation='SubWord'\n",
    "        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])))\n",
    "    return [b''.join(w[i:i+4]) for i in range(0,len(w),4)],trace\n",
    "\n",
    "# Trace each reversible AES stage, omitting MixColumns in the final encryption round.\n",
    "def aes(p,key,dec=False):\n",
    "    if len(p)!=16: raise ValueError('Exactly 16-byte AES block')\n",
    "    keys,_=expand(key); nr=len(keys)-1; s=p; trace=[row('Input',state=hexs(s))]\n",
    "    def snap(r,name): trace.append(row(f'{r} {name}',state=hexs(s)))\n",
    "    if not dec:\n",
    "        s=xor(s,keys[0]); snap(0,'AddRoundKey')\n",
    "        for r in range(1,nr+1):\n",
    "            s=bytes(sb(x) for x in s); snap(r,'SubBytes'); s=shift(s); snap(r,'ShiftRows')\n",
    "            if r<nr: s=mix(s); snap(r,'MixColumns')\n",
    "            s=xor(s,keys[r]); snap(r,'AddRoundKey')\n",
    "    else:\n",
    "        s=xor(s,keys[nr]); snap(nr,'AddRoundKey')\n",
    "        for r in range(nr-1,-1,-1):\n",
    "            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')\n",
    "            if r: s=mix(s,True); snap(r,'InvMixColumns')\n",
    "    return s,trace\n",
    "\n",
    "def n(s): return int(s,0)\n",
    "\n",
    "def b(s): return bytes.fromhex(s)\n",
    "\n",
    "def exact(s,size):\n",
    "    v=b(s)\n",
    "    if len(v)!=size: raise ValueError(f'Expected {size} bytes')\n",
    "    return v\n",
    "\n",
    "def pack(result,trace): return {'result':result,'trace':trace}\n",
    "\n",
    "EXTRA = {}\n",
    "\n",
    "def run(p):\n",
    "    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])\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ddb7692d",
   "metadata": {},
   "source": [
    "## Baseline experiment\n",
    "Read each field in the trace and predict the last output before running."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "991f1852",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ============================================================\n",
    "# CR19 | Run the verified baseline\n",
    "# Copyright © 2026/2027 Dr. Mohammad Alja’afreh\n",
    "# PSUT IoT Engineering Studio | Educational, synthetic inputs\n",
    "# ============================================================\n",
    "# All fields are strings so the same JSON can be used in the browser and WSL.\n",
    "PARAMS = {'plaintext': '00112233445566778899AABBCCDDEEFF', 'key': '000102030405060708090A0B0C0D0E0F'}\n",
    "# Inspect the exact intermediate states rather than relying on a black-box result.\n",
    "record = run(PARAMS)\n",
    "print(\"Result:\", record[\"result\"])\n",
    "for step in record[\"trace\"][:12]:\n",
    "    print(step)\n",
    "print(\"Total trace steps:\", len(record[\"trace\"]))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "150bd6ad",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ============================================================\n",
    "# CR19 | Verify the independently checked baseline\n",
    "# Copyright © 2026/2027 Dr. Mohammad Alja’afreh\n",
    "# PSUT IoT Engineering Studio | Educational, synthetic inputs\n",
    "# ============================================================\n",
    "# Expected values come from the curriculum audit and cross-runtime/reference tests.\n",
    "EXPECTED = {'ciphertext': '69C4E0D86A7B0430D8CDB78070B4C55A', 'recovered': '00112233445566778899AABBCCDDEEFF'}\n",
    "assert record[\"result\"] == EXPECTED, \"Baseline mismatch: inspect the first differing step\"\n",
    "print(\"Baseline verified\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "85f7fd74",
   "metadata": {},
   "source": [
    "## Controlled comparison\n",
    "Change key length 16,24,32 bytes. Keep plaintext. Measure every intermediate state and recovered plaintext. Independent variable = the edited input; dependent variable = measured output; controls = unchanged parameters. Compare the observed output with your prediction."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b864fe4d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ============================================================\n",
    "# CR19 | Perform a controlled comparison\n",
    "# Copyright © 2026/2027 Dr. Mohammad Alja’afreh\n",
    "# PSUT IoT Engineering Studio | Educational, synthetic inputs\n",
    "# ============================================================\n",
    "# Only one named input changes here; copy the baseline before editing.\n",
    "changed = dict(PARAMS)\n",
    "changed.update({'key': '000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F'})\n",
    "comparison = run(changed)\n",
    "print(\"Baseline:\", record[\"result\"])\n",
    "print(\"Changed:\", comparison[\"result\"])\n",
    "for step in comparison[\"trace\"][:6]:\n",
    "    print(step)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9c8502ee",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ============================================================\n",
    "# CR19 | Cross-check using the cryptography library\n",
    "# Copyright © 2026/2027 Dr. Mohammad Alja’afreh\n",
    "# PSUT IoT Engineering Studio | Educational, synthetic inputs\n",
    "# ============================================================\n",
    "try:\n",
    "    from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes as cm\n",
    "    key=bytes.fromhex(PARAMS[\"key\"]); data=bytes.fromhex(PARAMS[\"plaintext\"])\n",
    "    enc=Cipher(algorithms.AES(key),cm.ECB()).encryptor()\n",
    "    assert (enc.update(data)+enc.finalize()).hex().upper()==record[\"result\"][\"ciphertext\"]\n",
    "    print(\"Independent provider matches\")\n",
    "except ImportError:\n",
    "    print(\"Optional provider unavailable; install cryptography>=44 for this check\")\n"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "# ============================================================\n",
    "# CR19 | Run the assigned controlled trials\n",
    "# Copyright © 2026/2027 Dr. Mohammad Alja’afreh\n",
    "# PSUT IoT Engineering Studio\n",
    "# ============================================================\n",
    "# Each trial starts from the same baseline and changes only the specified field.\n",
    "# Record actual results and inspect the full trace when a prediction differs.\n",
    "TRIALS = [{}, {'key': '000102030405060708090A0B0C0D0E0F1011121314151617'}, {'key': '000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F'}]\n",
    "for trial_index, overrides in enumerate(TRIALS, 1):\n",
    "    settings = {**PARAMS, **overrides}\n",
    "    observation = run(settings)\n",
    "    print(f\"Trial {trial_index}: {settings}\")\n",
    "    print(observation[\"result\"])\n",
    "    # Show every intermediate state for this specific trial.\n",
    "    for step in observation[\"trace\"]:\n",
    "        print(step)\n",
    "\n",
    "# Verify the standardized AES-128, AES-192 and AES-256 known-answer outputs.\n",
    "expected_ciphertexts = [\"69C4E0D86A7B0430D8CDB78070B4C55A\", \"DDA97CA4864CDFE06EAF70A0EC0D7191\", \"8EA2B7CA516745BFEAFC49904B496089\"]\n",
    "for settings, expected in zip(TRIALS, expected_ciphertexts):\n",
    "    value = run({**PARAMS, **settings})[\"result\"]\n",
    "    assert value[\"ciphertext\"] == expected and value[\"recovered\"] == PARAMS[\"plaintext\"]\n",
    "print(\"All three known-answer tests passed\")\n"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "6e812a003c4a2366"
  },
  {
   "cell_type": "markdown",
   "id": "00f7a1ac",
   "metadata": {},
   "source": [
    "## Independent work (submit evidence, not just code)\n",
    "1. Restore the baseline and select an additional change described above. Predict what will happen.\n",
    "2. Run it in both environments, record baseline and modified results, and locate the first differing intermediate state.\n",
    "3. Produce a table with trial, changed input, fixed conditions, predicted value, measured value and discrepancy.\n",
    "4. **Independent assessment:** Run the lecture plaintext and key given in CR20, identify the first round-1 MixColumns state and the last round’s three transformations. Verify the ciphertext using the provider cell with the edited inputs. Justify using one calculated trace value or a counterexample.\n",
    "5. State one limitation: teaching parameters, synthetic input, lack of authentication, or runtime measurement limitations as applicable."
   ]
  }
 ],
 "metadata": {
  "colab": {
   "name": "CR19_aes-complete-cipher-and-inverse.ipynb",
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
