{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "1d2ac57d",
   "metadata": {},
   "source": [
    "# CR67 · HMAC inner and outer construction\n",
    "\n",
    "SHA-256 uses a 64-byte block. Normalize K to K′ by hashing keys longer than 64 bytes, then zero-padding. Compute inner=H((K′ XOR ipad)||m), tag=H((K′ XOR opad)||inner), where ipad=36 repeated and opad=5c repeated. HMAC authenticates under a shared key; it neither encrypts nor inherently prevents replay.\n",
    "\n",
    "## Worked calculation\n",
    "With 20 bytes of 0b and Hi There, RFC 4231 HMAC-SHA256 is b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7.\n",
    "\n",
    "## Baseline\n",
    "Inspect normalized key, both pads, inner digest and final tag for the reference case.\n",
    "\n",
    "## Controlled investigation\n",
    "Change only the message to Hi there; then restore it and compare a 65-byte synthetic key. Inspect the key normalization branch.\n",
    "\n",
    "**Evidence:** Key length, normalized key, pad values, inner digest and tag; compare with hmac.new.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "id": "concept067",
   "source": [
    "## HMAC construction\n",
    "\n",
    "HMAC provides keyed integrity and data-origin authentication among key holders. Its nested construction separates inner and outer hashing; it does not encrypt or prevent replay by itself.\n",
    "\n",
    "**Mathematical / protocol foundations:** For SHA-256, block size B=64 bytes. If \n",
    "\n",
    "**Worked teaching example and interpretation:** K|>B hash K, then pad to B with zeros. HMAC=H((K′⊕opad)||H((K′⊕ipad)||m)), ipad=36 and opad=5C repeated in hex.|For one-byte key 0xAA, first inner byte=9C, first outer byte=F6; all remaining key-pad bytes become 36 or 5C. Compute full inner and outer digests in simulator, verify with hmac.compare_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": "397b6cf0",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR67 | Educational algorithm and validation =====\n",
    "# CR67 | HMAC inner and outer construction\n",
    "# Execute the named operation; expose states and assert the laboratory invariant.\n",
    "import hashlib\n",
    "import hmac\n",
    "import json\n",
    "\n",
    "\n",
    "\n",
    "DEFAULT={'message': 'Hi There', 'keyhex': '0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b'}\n",
    "ALTERNATE={'message': 'Hi there'}\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",
    "    keyhex=params['keyhex']\n",
    "    if not isinstance(message,str) or len(message.encode())>512 or not isinstance(keyhex,str) or len(keyhex)>512 or len(keyhex)%2 or any(c not in \"0123456789abcdefABCDEF\" for c in keyhex): raise ValueError(\"Invalid message or key hex\")\n",
    "    m=message.encode();key=bytes.fromhex(keyhex);k=hashlib.sha256(key).digest() if len(key)>64 else key;k=k.ljust(64,b'\\0');ip=bytes(x^0x36 for x in k);op=bytes(x^0x5c for x in k);inner=hashlib.sha256(ip+m).digest();tag=hashlib.sha256(op+inner).hexdigest();steps=[{'normalized':k.hex()},{'ipad_xor':ip.hex(),'opad_xor':op.hex()},{'inner_digest':inner.hex()},{'outer_digest':tag}];result={'tag':tag,'library':hmac.new(key,m,hashlib.sha256).hexdigest()}\n",
    "    # Independently check the stated mathematical or protocol invariant.\n",
    "    assert result[\"tag\"]==result[\"library\"], \"verification failed\"\n",
    "    return {\"steps\":steps,\"result\":result}\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "46628c71",
   "metadata": {},
   "source": [
    "## Baseline calculation\n",
    "Inspect each trace row. The final result is separate from intermediate states."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "74421771",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR67 | 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": "e82919b8",
   "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": "f631885e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR67 | 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": [
    "# ===== CR67 | Controlled trials =====\n",
    "# Reinitialize defaults on every run. Record actual traces and compare invariants.\n",
    "for settings in [{'keyhex': 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'}, {'keyhex': ''}]:\n",
    "    trial = run(settings)\n",
    "    print(settings, trial[\"result\"])\n",
    "    for state in trial[\"steps\"]: print(state)\n"
   ],
   "id": "fbd8258419be7d08"
  },
  {
   "cell_type": "markdown",
   "id": "1f2739d6",
   "metadata": {},
   "source": [
    "## Student activity\n",
    "Change only the message to Hi there; then restore it and compare a 65-byte synthetic key. Inspect the key normalization branch.\n",
    "\n",
    "Submit Key length, normalized key, pad values, inner digest and tag; compare with hmac.new.\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
