{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "c6ff8497",
   "metadata": {},
   "source": [
    "# CR65 · File and firmware integrity\n",
    "\n",
    "A trusted reference digest can detect a modified local byte sequence. The verifier recomputes SHA-256 over received bytes and compares against that reference. A hash delivered by the same untrusted source is not independent authentication; signed firmware or a trusted authenticated manifest is required.\n",
    "\n",
    "## Worked calculation\n",
    "Flipping bit zero of F (0x46) produces G (0x47), changing the firmware digest without changing length.\n",
    "\n",
    "## Baseline\n",
    "Run FIRMWARE:v1 with byte offset zero. Record original and changed digest and verification decisions.\n",
    "\n",
    "## Controlled investigation\n",
    "Repeat at offsets 4 and 10 while keeping text fixed. Then use another synthetic text and compare against its own reference.\n",
    "\n",
    "**Evidence:** Byte offset, original and modified digests, decisions and explanation of the trusted reference requirement.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "id": "concept065",
   "source": [
    "## Firmware integrity\n",
    "\n",
    "A digest detects changes when compared to a reference obtained through a trusted channel. An attacker who can replace both file and digest defeats an unauthenticated check.\n",
    "\n",
    "**Mathematical / protocol foundations:** Compute H(file bytes), compare with trusted H_ref, and reject on mismatch. A signed manifest can bind digest, version and intended device identity.\n",
    "\n",
    "**Worked teaching example and interpretation:** Change one byte in a synthetic file and recompute. A different digest is evidence of a change, not attribution of its cause. Do not accept an untrusted replacement reference.\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": "8a436ade",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR65 | Educational algorithm and validation =====\n",
    "# CR65 | File and firmware integrity\n",
    "# Execute the named operation; expose states and assert the laboratory invariant.\n",
    "import hashlib\n",
    "import json\n",
    "\n",
    "\n",
    "\n",
    "DEFAULT={'text': 'FIRMWARE:v1', 'index': 0}\n",
    "ALTERNATE={'index': 4}\n",
    "\n",
    "def run(overrides=None):\n",
    "    # Merge only explicitly supplied inputs with the reference baseline.\n",
    "    params={**DEFAULT, **(overrides or {})}\n",
    "    text=params['text']\n",
    "    index=params['index']\n",
    "    if not isinstance(text,str) or not 1<=len(text.encode())<=512 or type(index) is not int or not 0<=index<len(text.encode()): raise ValueError(\"Byte outside input\")\n",
    "    original=text.encode();modified=bytearray(original);modified[index]^=1;a=hashlib.sha256(original).hexdigest();b=hashlib.sha256(modified).hexdigest();steps=[{'file':'original','length':len(original),'digest':a},{'file':'modified','offset':index,'digest':b}];result={'original_matches':hashlib.sha256(original).hexdigest()==a,'modified_matches':b==a}\n",
    "    # Independently check the stated mathematical or protocol invariant.\n",
    "    assert result[\"original_matches\"] and not result[\"modified_matches\"], \"verification failed\"\n",
    "    return {\"steps\":steps,\"result\":result}\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fb427497",
   "metadata": {},
   "source": [
    "## Baseline calculation\n",
    "Inspect each trace row. The final result is separate from intermediate states."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3c678005",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR65 | 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": "43e0a35b",
   "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": "08422e4d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR65 | 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": [
    "# ===== CR65 | Controlled trials =====\n",
    "# Reinitialize defaults on every run. Record actual traces and compare invariants.\n",
    "for settings in [{'index': 10}, {'text': 'FIRMWARE:v2'}]:\n",
    "    trial = run(settings)\n",
    "    print(settings, trial[\"result\"])\n",
    "    for state in trial[\"steps\"]: print(state)\n"
   ],
   "id": "a28369c395e29c61"
  },
  {
   "cell_type": "markdown",
   "id": "476d7e4a",
   "metadata": {},
   "source": [
    "## Student activity\n",
    "Repeat at offsets 4 and 10 while keeping text fixed. Then use another synthetic text and compare against its own reference.\n",
    "\n",
    "Submit Byte offset, original and modified digests, decisions and explanation of the trusted reference requirement.\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
