{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "416087f3",
   "metadata": {},
   "source": [
    "# CR61 · Truncated hash collision and birthday bound\n",
    "\n",
    "A collision is two distinct messages with the same digest. Preimage resistance and second-preimage resistance are different properties. For an ideal b-bit digest the approximate 50% collision threshold is sqrt(2 ln 2) × 2^(b/2). This exercise truncates SHA-256 intentionally to 4–16 bits and searches only synthetic classroom strings. It is not a collision attack on full SHA-256.\n",
    "\n",
    "## Worked calculation\n",
    "An 8-bit prefix has 256 possibilities; the approximate 50% threshold is 19 samples. The first collision count depends on the selected sequence.\n",
    "\n",
    "## Baseline\n",
    "Choose b=8, run the classroom sequence and record the two distinct sample indices and equal prefix.\n",
    "\n",
    "## Controlled investigation\n",
    "Repeat for 4, 12 and 16 bits. Use the same classroom message generator and compare observed first collision count with the theoretical scale.\n",
    "\n",
    "**Evidence:** Prefix width, collision indices, number of samples and theoretical threshold. Explain why one run does not estimate a probability reliably.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "id": "concept061",
   "source": [
    "## Hash security and birthday scaling\n",
    "\n",
    "Preimage asks for an input matching a specified digest; second-preimage fixes an existing input; collision asks for any two distinct inputs with equal digest.\n",
    "\n",
    "**Mathematical / protocol foundations:** For an ideal n-bit hash, generic preimage cost scales about 2ⁿ, generic collision about 2^(n/2). Probability of at least one collision among k random digests is approximately 1−exp(−k(k−1)/(2·2ⁿ)).\n",
    "\n",
    "**Worked teaching example and interpretation:** For an intentionally truncated 8-bit digest, roughly 19–20 samples give around one-half collision probability. This does not transfer to full-strength SHA-256.\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": "8a75accf",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR61 | Educational algorithm and validation =====\n",
    "# CR61 | Truncated hash collision and birthday bound\n",
    "# Execute the named operation; expose states and assert the laboratory invariant.\n",
    "import hashlib\n",
    "import json\n",
    "\n",
    "\n",
    "\n",
    "DEFAULT={'bits': 8}\n",
    "ALTERNATE={'bits': 12}\n",
    "\n",
    "def run(overrides=None):\n",
    "    # Merge only explicitly supplied inputs with the reference baseline.\n",
    "    params={**DEFAULT, **(overrides or {})}\n",
    "    bits=params['bits']\n",
    "    if type(bits) is not int or not 4<=bits<=16: raise ValueError(\"Choose 4–16 prefix bits\")\n",
    "    seen={};steps=[]\n",
    "    for i in range(10000):\n",
    "        d=int.from_bytes(hashlib.sha256(f'classroom-{i}'.encode()).digest(),'big')>>(256-bits)\n",
    "        if i<20:steps.append({'sample':i,'digest_prefix':d})\n",
    "        if d in seen:break\n",
    "        seen[d]=i\n",
    "    steps.append({'first':seen[d],'second':i,'prefix':d});result={'samples':i+1,'collision':seen[d]!=i,'prefix_bits':bits}\n",
    "    # Independently check the stated mathematical or protocol invariant.\n",
    "    assert result[\"collision\"], \"verification failed\"\n",
    "    return {\"steps\":steps,\"result\":result}\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b92b92d7",
   "metadata": {},
   "source": [
    "## Baseline calculation\n",
    "Inspect each trace row. The final result is separate from intermediate states."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7affba5c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR61 | 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": "aa610bcf",
   "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": "cf6f3a7c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR61 | 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": [
    "# ===== CR61 | Controlled trials =====\n",
    "# Reinitialize defaults on every run. Record actual traces and compare invariants.\n",
    "for settings in [{'bits': 12}, {'bits': 16}]:\n",
    "    trial = run(settings)\n",
    "    print(settings, trial[\"result\"])\n",
    "    for state in trial[\"steps\"]: print(state)\n"
   ],
   "id": "d5e4c85a70f73210"
  },
  {
   "cell_type": "markdown",
   "id": "88d8f6b4",
   "metadata": {},
   "source": [
    "## Student activity\n",
    "Repeat for 4, 12 and 16 bits. Use the same classroom message generator and compare observed first collision count with the theoretical scale.\n",
    "\n",
    "Submit Prefix width, collision indices, number of samples and theoretical threshold. Explain why one run does not estimate a probability reliably.\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
