{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "40abbe38",
   "metadata": {},
   "source": [
    "# CR71 · ElGamal signature mathematics\n",
    "\n",
    "Use a prime p, primitive root g and private x; y=g^x mod p. Choose k coprime to p−1. r=g^k mod p and s=k⁻¹(h−xr) mod (p−1). Verify g^h ≡ y^r r^s (mod p). The small example is for arithmetic only; never use these parameters or chosen signing nonces in real systems.\n",
    "\n",
    "## Worked calculation\n",
    "For p=19, g=10, x=5, k=5, h=7, compute k inverse modulo 18 and both sides of the verification equation.\n",
    "\n",
    "## Baseline\n",
    "Run the baseline and trace y, k inverse, r, s and both verification sides.\n",
    "\n",
    "## Controlled investigation\n",
    "Change h to 8, then k to 7 with h=7; test k=6 and explain the rejection due to no inverse.\n",
    "\n",
    "**Evidence:** Public value, signature pair, inverse, both sides and invalid-nonce observation.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "id": "concept071",
   "source": [
    "## ElGamal signature algebra\n",
    "\n",
    "The historical ElGamal signature uses the discrete-log group and an ephemeral exponent invertible modulo p−1. Signature equations differ from ElGamal encryption.\n",
    "\n",
    "**Mathematical / protocol foundations:** r=gᵏ mod p; s=k⁻¹(H(m)−xr) mod(p−1). Verify g^H(m)≡Yʳrˢ mod p. This follows because xr+ks≡H(m) mod(p−1).\n",
    "\n",
    "**Worked teaching example and interpretation:** With synthetic p=23,g=5,x=3,k=7,z=9: r=17, k⁻¹ mod22=19, s=(9−51)·19 mod22=16. Both sides equal 11 modulo23. Toy values are not deployment parameters.\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": "805cbb00",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR71 | Educational algorithm and validation =====\n",
    "# CR71 | ElGamal signature mathematics\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={'p': 19, 'g': 10, 'x': 5, 'k': 5, 'digest': 7}\n",
    "ALTERNATE={'digest': 8}\n",
    "\n",
    "def run(overrides=None):\n",
    "    # Merge only explicitly supplied inputs with the reference baseline.\n",
    "    params={**DEFAULT, **(overrides or {})}\n",
    "    p=params['p']\n",
    "    g=params['g']\n",
    "    x=params['x']\n",
    "    k=params['k']\n",
    "    digest=params['digest']\n",
    "    if not (all(type(z) is int for z in (p,g,x,k,digest)) and 5<=p<=997 and all(p%j for j in range(2,int(p**.5)+1)) and 2<=g<p and len({pow(g,j,p) for j in range(p-1)})==p-1 and 1<=x<=p-2 and 1<=k<=p-2 and 0<=digest<=p-2): raise ValueError(\"Invalid prime, generator, secret, nonce or digest\")\n",
    "    y=pow(g,x,p);r=pow(g,k,p);s=inv(k,p-1)*(digest-x*r)%(p-1);left=pow(g,digest,p);right=pow(y,r,p)*pow(r,s,p)%p;steps=[{'public':y,'k_inverse':inv(k,p-1)},{'r':r,'s':s},{'left':left,'right':right}];result={'valid':left==right,'altered_rejected':pow(g,digest+1,p)!=right}\n",
    "    # Independently check the stated mathematical or protocol invariant.\n",
    "    assert result[\"valid\"] and result[\"altered_rejected\"], \"verification failed\"\n",
    "    return {\"steps\":steps,\"result\":result}\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e24fd161",
   "metadata": {},
   "source": [
    "## Baseline calculation\n",
    "Inspect each trace row. The final result is separate from intermediate states."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "65fcbe86",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR71 | 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": "b1376ab5",
   "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": "f4b117cc",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR71 | 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": [
    "# ===== CR71 | Controlled trials =====\n",
    "# Reinitialize defaults on every run. Record actual traces and compare invariants.\n",
    "for settings in [{'k': 7}, {'digest': 0}]:\n",
    "    trial = run(settings)\n",
    "    print(settings, trial[\"result\"])\n",
    "    for state in trial[\"steps\"]: print(state)\n"
   ],
   "id": "1efe5f222f25803e"
  },
  {
   "cell_type": "markdown",
   "id": "09fb0111",
   "metadata": {},
   "source": [
    "## Student activity\n",
    "Change h to 8, then k to 7 with h=7; test k=6 and explain the rejection due to no inverse.\n",
    "\n",
    "Submit Public value, signature pair, inverse, both sides and invalid-nonce observation.\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
