{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "72eb29dd",
   "metadata": {},
   "source": [
    "# CR59 · Hashing versus encoding and digest families\n",
    "\n",
    "Encoding changes representation and is reversible without a secret. Hashing maps arbitrary bytes to a fixed-size digest; it is not encryption or sender authentication. MD5 and SHA-1 are historical, collision-broken algorithms, not suitable for new security designs. SHA-256, SHA-512 and SHA3-256 have different digest sizes and constructions. UTF-8 byte length may differ from character count.\n",
    "\n",
    "## Worked calculation\n",
    "For abc, hexadecimal is 616263 and Base64 is YWJj. SHA-256 is ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad.\n",
    "\n",
    "## Baseline\n",
    "Run temperature=25.0 and inspect both encodings and all five digests. Decode Base64 independently.\n",
    "\n",
    "## Controlled investigation\n",
    "Change the text to temperature=26.0, then abc and a non-ASCII example. Keep the algorithms fixed; compare encoding length, digest length and changes.\n",
    "\n",
    "**Evidence:** A table of UTF-8 bytes, reversible encodings and five digest lengths; explain why a digest is not authentication.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "id": "concept059",
   "source": [
    "## Hashing versus encoding\n",
    "\n",
    "A hash maps arbitrary length data to a fixed digest. Encoding changes representation and is reversible without secrets; encryption is reversible with an appropriate key. Hashing alone does not authenticate a sender.\n",
    "\n",
    "**Mathematical / protocol foundations:** For a secure n-bit hash, digest space has 2ⁿ values. Preimage, second-preimage and collision resistance describe different tasks. SHA-2 and SHA-3 are distinct standardized families; MD5/SHA-1 are obsolete for collision-sensitive uses.\n",
    "\n",
    "**Worked teaching example and interpretation:** UTF-8 A is byte 41 (hex); Base64 QQ==. SHA-256 produces 32 bytes regardless of input length; no decoding operation recovers the original from its digest.\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": "7b9a82b6",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR59 | Educational algorithm and validation =====\n",
    "# CR59 | Hashing versus encoding and digest families\n",
    "# Execute the named operation; expose states and assert the laboratory invariant.\n",
    "import hashlib\n",
    "import base64\n",
    "import json\n",
    "\n",
    "\n",
    "\n",
    "DEFAULT={'message': 'temperature=25.0'}\n",
    "ALTERNATE={'message': 'temperature=26.0'}\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",
    "    if not isinstance(message,str) or len(message.encode())>512: raise ValueError(\"Use 0–512 UTF-8 bytes\")\n",
    "    m=message.encode();steps=[{'encoding':'hex','output':m.hex()},{'encoding':'base64','output':base64.b64encode(m).decode()}]\n",
    "    for alg in ('md5','sha1','sha256','sha512','sha3_256'):\n",
    "        h=hashlib.new(alg,m);steps.append({'algorithm':alg,'digest':h.hexdigest(),'bits':h.digest_size*8})\n",
    "    result={'decoded':base64.b64decode(steps[1]['output']).decode(),'sha256':hashlib.sha256(m).hexdigest()}\n",
    "    # Independently check the stated mathematical or protocol invariant.\n",
    "    assert result[\"decoded\"]==message and len(result[\"sha256\"])==64, \"verification failed\"\n",
    "    return {\"steps\":steps,\"result\":result}\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bde1ee65",
   "metadata": {},
   "source": [
    "## Baseline calculation\n",
    "Inspect each trace row. The final result is separate from intermediate states."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4f10f8f9",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR59 | 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": "bd4f19a0",
   "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": "8217857b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR59 | 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": [
    "# ===== CR59 | Controlled trials =====\n",
    "# Reinitialize defaults on every run. Record actual traces and compare invariants.\n",
    "for settings in [{'message': 'abc'}, {'message': 'PSUT – IoT'}]:\n",
    "    trial = run(settings)\n",
    "    print(settings, trial[\"result\"])\n",
    "    for state in trial[\"steps\"]: print(state)\n"
   ],
   "id": "451ca3d3eba5031b"
  },
  {
   "cell_type": "markdown",
   "id": "fb6cde75",
   "metadata": {},
   "source": [
    "## Student activity\n",
    "Change the text to temperature=26.0, then abc and a non-ASCII example. Keep the algorithms fixed; compare encoding length, digest length and changes.\n",
    "\n",
    "Submit A table of UTF-8 bytes, reversible encodings and five digest lengths; explain why a digest is not authentication.\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
