{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "846ff282",
   "metadata": {},
   "source": [
    "# CR72 · DSA historical signature verification\n",
    "\n",
    "For this small fixed DSA fixture p=23, q=11, g=4, x=3, k=6, h=9, sign using r=(g^k mod p) mod q and s=k⁻¹(h+xr) mod q. Verify with w=s⁻¹ mod q, u1=hw mod q, u2=rw mod q, v=((g^u1 y^u2 mod p) mod q). A tiny digest domain can admit accidental verification collisions. DSA is historical and not recommended for new signature generation.\n",
    "\n",
    "## Worked calculation\n",
    "The fixture is generated from h=9; verification succeeds for that representative. Other representatives must be evaluated by the actual equation, not presumed to fail.\n",
    "\n",
    "## Baseline\n",
    "Verify digest 9; inspect r,s,w,u1,u2,v and compare v with r.\n",
    "\n",
    "## Controlled investigation\n",
    "Enumerate digest representatives 0–10 using the same signature fixture. Record every accepted representative and explain tiny-domain limitations.\n",
    "\n",
    "**Evidence:** Verification table, accepted set and explanation of why toy DSA cannot establish real-world signature security.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "id": "concept072",
   "source": [
    "## DSA historical construction\n",
    "\n",
    "DSA uses a subgroup of prime order q dividing p−1. Private x, public y=gˣ mod p. Signing historically uses a fresh invertible ephemeral k; DSA generation is legacy under current NIST guidance.\n",
    "\n",
    "**Mathematical / protocol foundations:** r=(gᵏ mod p) mod q; s=k⁻¹(z+xr) mod q. Verify w=s⁻¹,u1=zw,u2=rw mod q; v=((g^u1 y^u2 mod p) mod q), accept when v=r and ranges valid.\n",
    "\n",
    "**Worked teaching example and interpretation:** The displayed small-domain trace illustrates the verification equality; modifying the digest may cause rejection, though toy values can collide. Modern practical signatures use approved schemes and library APIs.\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": "12a47ebf",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR72 | Educational algorithm and validation =====\n",
    "# CR72 | DSA historical signature verification\n",
    "# Execute the named operation; expose states and assert the laboratory invariant.\n",
    "import json\n",
    "\n",
    "def egcd(a,b):\n",
    "    # Track coefficients of a and b alongside the successive remainders.\n",
    "    r,s,t=a,1,0; nr,ns,nt=b,0,1; steps=[]\n",
    "    while nr:\n",
    "        q=r//nr; steps.append({'dividend':r,'divisor':nr,'quotient':q,'remainder':r%nr,'coeff_a':s-q*ns,'coeff_b':t-q*nt})\n",
    "        r,nr=nr,r-q*nr; s,ns=ns,s-q*ns; t,nt=nt,t-q*nt\n",
    "    return r,s,t,steps\n",
    "\n",
    "def inv(a,m):\n",
    "    g,x,_,_=egcd(a%m,m)\n",
    "    if g!=1: raise ValueError('No inverse: gcd is not 1')\n",
    "    return x%m\n",
    "\n",
    "DEFAULT={'digest': 9}\n",
    "ALTERNATE={'digest': 10}\n",
    "\n",
    "def run(overrides=None):\n",
    "    # Merge only explicitly supplied inputs with the reference baseline.\n",
    "    params={**DEFAULT, **(overrides or {})}\n",
    "    digest=params['digest']\n",
    "    if type(digest) is not int or not 0<=digest<=10: raise ValueError(\"Digest representative 0–10\")\n",
    "    p,q,g,y,r,s=23,11,4,18,7,1\n",
    "    # Generate a fixed classroom fixture from x=3,k=6,H=9, then verify the selected digest.\n",
    "    x=3;k=6;y=pow(g,x,p);r=pow(g,k,p)%q;s=inv(k,q)*(9+x*r)%q\n",
    "    w=inv(s,q);u1=digest*w%q;u2=r*w%q;v=(pow(g,u1,p)*pow(y,u2,p)%p)%q;steps=[{'p':p,'q':q,'g':g,'y':y,'r':r,'s':s},{'w':w,'u1':u1,'u2':u2,'v':v}];result={'valid':v==r}\n",
    "    # Independently check the stated mathematical or protocol invariant.\n",
    "    assert digest!=9 or result[\"valid\"], \"baseline verification failed\"\n",
    "    return {\"steps\":steps,\"result\":result}\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bf780233",
   "metadata": {},
   "source": [
    "## Baseline calculation\n",
    "Inspect each trace row. The final result is separate from intermediate states."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9958db8d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR72 | 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": "67d3d2da",
   "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": "31a1fcf8",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR72 | 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": [
    "# ===== CR72 | Controlled trials =====\n",
    "# Reinitialize defaults on every run. Record actual traces and compare invariants.\n",
    "for settings in [{'digest': 0}, {'digest': 5}]:\n",
    "    trial = run(settings)\n",
    "    print(settings, trial[\"result\"])\n",
    "    for state in trial[\"steps\"]: print(state)\n"
   ],
   "id": "8dbaf8dd594128b8"
  },
  {
   "cell_type": "markdown",
   "id": "bb3a2bbf",
   "metadata": {},
   "source": [
    "## Student activity\n",
    "Enumerate digest representatives 0–10 using the same signature fixture. Record every accepted representative and explain tiny-domain limitations.\n",
    "\n",
    "Submit Verification table, accepted set and explanation of why toy DSA cannot establish real-world signature security.\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
