{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "1f787985",
   "metadata": {},
   "source": [
    "# CR51 · ElGamal encryption\n",
    "\n",
    "Recipient publishes Y=gˣ mod q. Sender selects ephemeral k and computes C₁=gᵏ and mask K=Yᵏ mod q; C₂=mK mod q. Recipient computes K=C₁ˣ then m=C₂K⁻¹ mod q. Textbook ElGamal does not authenticate.\n",
    "\n",
    "## Worked calculation\n",
    "q=19,g=10,xa=5,m=17,k=6: Y=3, K=7, C₁=11, C₂=5; inverse of 7 mod 19 is 11; recovered=17.\n",
    "\n",
    "## Baseline\n",
    "Calculate Y, mask, ciphertext components and inverse; verify identical sender and recipient masks.\n",
    "\n",
    "## Controlled investigation\n",
    "Set k=3 then 4 holding q,g,xa,m fixed. Compare ciphertext pairs and explain the role of ephemeral randomness.\n",
    "\n",
    "**Evidence:** Y,k, sender/recipient mask, inverse, C₁,C₂ and recovered representative.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "id": "concept051",
   "source": [
    "## ElGamal encryption\n",
    "\n",
    "ElGamal uses a receiver public value and fresh ephemeral exponent to produce a masking value. Decryption reconstructs the mask using the private exponent and removes it by modular inversion.\n",
    "\n",
    "**Mathematical / protocol foundations:** Y=gˣ mod p; C1=gᵏ mod p; C2=M·Yᵏ mod p; M=C2·(C1ˣ)⁻¹ mod p. For p=19,g=10,x=5,k=6,M=17: Y=3,C1=11,mask=7,C2=5.\n",
    "\n",
    "**Worked teaching example and interpretation:** 7⁻¹ mod19=11; 5·11≡17. Fresh k is necessary; toy parameters and unauthenticated textbook construction are not suitable for deployment.\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": "b5e9e102",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR51 | Educational algorithm and validation =====\n",
    "# CR51 | ElGamal lecture encryption\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={'q': 19, 'g': 10, 'xa': 5, 'm': 17, 'k': 6}\n",
    "ALTERNATE={'k': 3}\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",
    "    m=params['m']\n",
    "    k=params['k']\n",
    "    if not (all(type(x) is int for x in (q,g,xa,k,m)) 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<=k<=q-2 and 1<=m<q and len({pow(g,i,q) for i in range(q-1)})==q-1): raise ValueError('Invalid prime, generator or private exponent')\n",
    "    if not 1<=m<q or not 1<=k<q-1:raise ValueError('nonzero message and valid ephemeral exponent required')\n",
    "    Y=pow(g,xa,q);K=pow(Y,k,q);c1=pow(g,k,q);c2=K*m%q;K2=pow(c1,xa,q);ki=inv(K2,q);recovered=c2*ki%q\n",
    "    steps=[{'public_key':Y},{'mask':K,'c1':c1,'c2':c2},{'reconstructed_mask':K2,'inverse':ki,'recovered':recovered}];result={'ciphertext':[c1,c2],'recovered':recovered}\n",
    "    # Independently check the stated mathematical or protocol invariant.\n",
    "    assert result[\"recovered\"]==m, \"verification failed\"\n",
    "    return {\"steps\":steps,\"result\":result}\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cc3fc5ac",
   "metadata": {},
   "source": [
    "## Baseline calculation\n",
    "Inspect each trace row. The final result is separate from intermediate states."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4ae869ca",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR51 | 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": "dc4cf63a",
   "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": "b967193a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR51 | 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": [
    "# ===== CR51 | Controlled trials =====\n",
    "# Reinitialize defaults on every run. Record actual traces and compare invariants.\n",
    "for settings in [{'k': 4}]:\n",
    "    trial = run(settings)\n",
    "    print(settings, trial[\"result\"])\n",
    "    for state in trial[\"steps\"]: print(state)\n"
   ],
   "id": "5449199983bc3aa7"
  },
  {
   "cell_type": "markdown",
   "id": "0e7b4913",
   "metadata": {},
   "source": [
    "## Student activity\n",
    "Set k=3 then 4 holding q,g,xa,m fixed. Compare ciphertext pairs and explain the role of ephemeral randomness.\n",
    "\n",
    "Submit Y,k, sender/recipient mask, inverse, C₁,C₂ and recovered representative.\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
