{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "8a75d6b6",
   "metadata": {},
   "source": [
    "# CR49 · Diffie–Hellman key agreement\n",
    "\n",
    "For public prime q and generator g, Alice sends A=gˣᵃ mod q and Bob B=gˣᵇ mod q. Both compute g^(xa·xb) mod q independently. Private exponents stay local; DH alone does not authenticate peers or directly encrypt messages.\n",
    "\n",
    "## Worked calculation\n",
    "q=23,g=5,xa=6,xb=15 gives A=8, B=19, B⁶ mod 23=2 and A¹⁵ mod 23=2.\n",
    "\n",
    "## Baseline\n",
    "Predict public values; trace both parties, verify matching secrets without transmitting private values.\n",
    "\n",
    "## Controlled investigation\n",
    "Change only xb to 7 then 9. Keep q,g,xa fixed. Compare public values and shared-secret equality.\n",
    "\n",
    "**Evidence:** Public parameters, classroom private values, A/B, both derived secrets and match decision.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "id": "concept049",
   "source": [
    "## Diffie–Hellman key agreement\n",
    "\n",
    "Both parties publish values derived from secret exponents in a common group. The equal shared secret follows from commutativity of exponent multiplication; the exchange alone does not establish identity.\n",
    "\n",
    "**Mathematical / protocol foundations:** A=gᵃ mod p,B=gᵇ mod p; S=Bᵃ=Aᵇ=g^(ab) mod p. For p=23,g=5,a=6,b=15, A=8,B=19.\n",
    "\n",
    "**Worked teaching example and interpretation:** 19⁶ mod23=2 and 8¹⁵ mod23=2. Public values may be observed; private exponents and shared secret are not transmitted. Derive application keys with a KDF and authenticate the peers.\n",
    "\n",
    "Compare corresponding states; for randomized or timed runs compare invariants rather than literal random bytes or timings.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2cec3d53",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR49 | Educational algorithm and validation =====\n",
    "# CR49 | Diffie–Hellman lecture key agreement\n",
    "# Execute the named operation; expose states and assert the laboratory invariant.\n",
    "import json\n",
    "\n",
    "\n",
    "\n",
    "DEFAULT={'q': 23, 'g': 5, 'xa': 6, 'xb': 15}\n",
    "ALTERNATE={'xb': 7}\n",
    "\n",
    "def run(overrides=None):\n",
    "    # Merge only explicitly supplied inputs with the reference baseline.\n",
    "    params={**DEFAULT, **(overrides or {})}\n",
    "    q=params['q']\n",
    "    g=params['g']\n",
    "    xa=params['xa']\n",
    "    xb=params['xb']\n",
    "    if not (all(type(x) is int for x in (q,g,xa,xb)) and 5<=q<=997 and all(q%i for i in range(2,int(q**0.5)+1)) and 2<=g<q and 1<=xa<=q-2 and 1<=xb<=q-2 and len({pow(g,i,q) for i in range(q-1)})==q-1): raise ValueError('Invalid prime, generator or private exponent')\n",
    "    A=pow(g,xa,q);B=pow(g,xb,q);ka=pow(B,xa,q);kb=pow(A,xb,q)\n",
    "    steps=[{'actor':'Alice','public':A},{'actor':'Bob','public':B},{'actor':'Alice','received':B,'shared':ka},{'actor':'Bob','received':A,'shared':kb}];result={'A':A,'B':B,'shared':ka,'match':ka==kb}\n",
    "    # Independently check the stated mathematical or protocol invariant.\n",
    "    assert result[\"match\"], \"verification failed\"\n",
    "    return {\"steps\":steps,\"result\":result}\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3453e7d6",
   "metadata": {},
   "source": [
    "## Baseline calculation\n",
    "Inspect each trace row. The final result is separate from intermediate states."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dc24754d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR49 | Execute the baseline =====\n",
    "# ===== Execute the baseline =====\n",
    "# Run the default worked example; inspect the intermediate states in order.\n",
    "baseline=run()\n",
    "for step in baseline[\"steps\"]: print(step)\n",
    "print(\"Result:\",baseline[\"result\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7e24bc45",
   "metadata": {},
   "source": [
    "## Controlled comparison\n",
    "Change the indicated input; leave other inputs unchanged. A baseline is the reference run. A mathematical verification substitutes the result back into its defining equation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1ecd41a2",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR49 | Compare the specified alternative =====\n",
    "# ===== Compare the specified alternative =====\n",
    "# Override only the chosen input(s), leaving remaining parameters at baseline.\n",
    "comparison=run(ALTERNATE)\n",
    "for step in comparison[\"steps\"]: print(step)\n",
    "print(\"Result:\",comparison[\"result\"])"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "# ===== CR49 | Controlled trials =====\n",
    "# Reinitialize defaults on every run. Record actual traces and compare invariants.\n",
    "for settings in [{'xb': 9}]:\n",
    "    trial = run(settings)\n",
    "    print(settings, trial[\"result\"])\n",
    "    for state in trial[\"steps\"]: print(state)\n"
   ],
   "id": "c83f4fec13b42690"
  },
  {
   "cell_type": "markdown",
   "id": "5eae5dc1",
   "metadata": {},
   "source": [
    "## Student activity\n",
    "Change only xb to 7 then 9. Keep q,g,xa fixed. Compare public values and shared-secret equality.\n",
    "\n",
    "Submit Public parameters, classroom private values, A/B, both derived secrets and match decision.\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
