{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "1eac0217",
   "metadata": {},
   "source": [
    "# CR62 · Hash avalanche: sensor message\n",
    "\n",
    "A controlled comparison changes one input bit while keeping message length and the hash algorithm fixed. Hamming distance counts differing digest bits; divide by digest width and multiply by 100. The bit index starts at the least significant bit of UTF-8 byte zero. Strong avalanche alone does not prove collision resistance.\n",
    "\n",
    "## Worked calculation\n",
    "For a 256-bit digest, a Hamming distance of 128 corresponds to 50%. SHA-512 uses a 512-bit denominator.\n",
    "\n",
    "## Baseline\n",
    "Use temperature=25.0 and bit 0; record original and modified digests for all three algorithms.\n",
    "\n",
    "## Controlled investigation\n",
    "Repeat at bits 1, 9 and 31 with identical starting message. Compare percentages, not raw counts across digest widths.\n",
    "\n",
    "**Evidence:** A per-algorithm, per-bit table and a plot of percentage changed; discuss variability and limits.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "id": "concept062",
   "source": [
    "## Hash avalanche\n",
    "\n",
    "Hamming distance between equal-length digests measures sensitivity to a small input perturbation. Use a fixed input length and a one-bit change to avoid confounding.\n",
    "\n",
    "**Mathematical / protocol foundations:** d=popcount(H(m)⊕H(m′)); percentage=100d/n. Compare the entire digest, not just hexadecimal characters that differ.\n",
    "\n",
    "**Worked teaching example and interpretation:** For bytes 0x00 and 0x81, XOR=81 and d=2 of 8=25%. Hex characters are four bits each, so counting differing hex digits is not Hamming distance. Avalanche alone is not collision resistance.\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": "4cb2b52b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR62 | Educational algorithm and validation =====\n",
    "# CR62 | Hash avalanche: sensor message\n",
    "# Execute the named operation; expose states and assert the laboratory invariant.\n",
    "import hashlib\n",
    "import json\n",
    "\n",
    "\n",
    "\n",
    "DEFAULT={'message': 'temperature=25.0', 'bit': 0}\n",
    "ALTERNATE={'bit': 9}\n",
    "\n",
    "def run(overrides=None):\n",
    "    # Merge only explicitly supplied inputs with the reference baseline.\n",
    "    params={**DEFAULT, **(overrides or {})}\n",
    "    message=params['message']\n",
    "    bit=params['bit']\n",
    "    if not isinstance(message,str) or not 1<=len(message.encode())<=512 or type(bit) is not int or not 0<=bit<8*len(message.encode()): raise ValueError(\"Bit outside input\")\n",
    "    m=message.encode();v=bytearray(m);v[bit//8]^=1<<(bit%8);steps=[]\n",
    "    for alg in ('sha256','sha512','sha3_256'):\n",
    "        x=hashlib.new(alg,m).digest();y=hashlib.new(alg,v).digest();dist=sum((a^b).bit_count() for a,b in zip(x,y));steps.append({'algorithm':alg,'original':x.hex(),'changed':y.hex(),'distance':dist,'percentage':round(100*dist/(8*len(x)),3)})\n",
    "    result={'changed_bit':bit,'algorithms':len(steps)}\n",
    "    # Independently check the stated mathematical or protocol invariant.\n",
    "    assert all(0<=s[\"percentage\"]<=100 for s in steps), \"verification failed\"\n",
    "    return {\"steps\":steps,\"result\":result}\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "130ce966",
   "metadata": {},
   "source": [
    "## Baseline calculation\n",
    "Inspect each trace row. The final result is separate from intermediate states."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f46cb8ed",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR62 | 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": "bc0f5fab",
   "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": "2c24afbb",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR62 | 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": [
    "# ===== CR62 | Controlled trials =====\n",
    "# Reinitialize defaults on every run. Record actual traces and compare invariants.\n",
    "for settings in [{'bit': 9}, {'bit': 31}]:\n",
    "    trial = run(settings)\n",
    "    print(settings, trial[\"result\"])\n",
    "    for state in trial[\"steps\"]: print(state)\n"
   ],
   "id": "ab8213d61cafff13"
  },
  {
   "cell_type": "markdown",
   "id": "a8bd1d0b",
   "metadata": {},
   "source": [
    "## Student activity\n",
    "Repeat at bits 1, 9 and 31 with identical starting message. Compare percentages, not raw counts across digest widths.\n",
    "\n",
    "Submit A per-algorithm, per-bit table and a plot of percentage changed; discuss variability and limits.\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
