{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "f560c9f8",
   "metadata": {},
   "source": [
    "# CR73 · Key lifecycle and session-key distribution\n",
    "\n",
    "Long-term keys authenticate identities; session keys protect one session. A KDC is a trusted intermediary. Rotation, expiration and revocation constrain use. This explicit model checks key validity and freshness before release.\n",
    "\n",
    "Foundational concepts; prerequisite: CR49, CR67.\n",
    "\n",
    "**Scope:** Protocol lifecycle model, not a KDC implementation."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "id": "concept073",
   "source": [
    "## Key lifecycle and distribution\n",
    "\n",
    "Keys have purpose, owner, activation, expiration and revocation state. A long-term key authenticates or protects establishment of short-lived session keys; separate keys by purpose.\n",
    "\n",
    "**Mathematical / protocol foundations:** A simplified issuance policy is active AND not revoked AND now<expiry. Real wrapping uses authenticated encryption, a unique nonce and associated context; key destruction and rotation require operational controls.\n",
    "\n",
    "**Worked teaching example and interpretation:** For expiry 20, now 19 and not revoked allows issuance under the model; now 20 rejects. Authenticated wrapped session material must verify before use. This is not a full production KDC.\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": "afa42ba7",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR73 | Algorithm and verification =====\n",
    "# ===== Algorithm and verification =====\n",
    "# The function returns the exact intermediate states and verifies the invariant.\n",
    "import json\n",
    "\n",
    "\n",
    "\n",
    "DEFAULT={'now': 5, 'expires': 10, 'revoked': False}\n",
    "ALTERNATE={'now': 11}\n",
    "\n",
    "def run(overrides=None):\n",
    "    # Merge only explicitly supplied inputs with the reference baseline.\n",
    "    params={**DEFAULT, **(overrides or {})}\n",
    "    now=params['now']\n",
    "    expires=params['expires']\n",
    "    revoked=params['revoked']\n",
    "    steps=[{'actor':'client','request':'session key'},{'actor':'KDC','long_term_key_valid':now<expires and not revoked},{'actor':'KDC','fresh_nonce':True}];issued=now<expires and not revoked;steps.append({'actor':'KDC','decision':'issue wrapped session key' if issued else 'deny'});result={'issued':issued}\n",
    "    # Independently check the stated mathematical or protocol invariant.\n",
    "    assert result[\"issued\"]==(now<expires and not revoked), \"verification failed\"\n",
    "    return {\"steps\":steps,\"result\":result}\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1de6c907",
   "metadata": {},
   "source": [
    "## Baseline calculation\n",
    "Inspect each trace row. The final result is separate from intermediate states."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f24dcaf8",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR73 | 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": "ce647152",
   "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": "5f306754",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR73 | 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": "markdown",
   "id": "abf4f6d4",
   "metadata": {},
   "source": [
    "## Student activity\n",
    "Change the clock from 5 to 11, keeping expiration fixed. Repeat revoked=true in Python. Draw the trust boundary and identify keys never sent in plaintext.\n",
    "\n",
    "Submit a baseline/alternate table, trace evidence and a justification. Identify which checks passed and what they do not prove."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Extended practical: authenticated session-key distribution\n",
    "Run this standalone example with fresh local keys. Compare baseline, expired and revoked cases; inspect the authentication-tag rejection. Do not log key material."
   ],
   "id": "22c9044f0789e359"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "# ===== CR73 | Dependency check =====\n",
    "import importlib.util\n",
    "assert importlib.util.find_spec(\"cryptography\"), \"Install cryptography with %pip install cryptography\"\n"
   ],
   "id": "8284d13ba00ddc96"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "# ===== CR73 | Extended local implementation =====\n",
    "# ------------------------------------------------------------\n",
    "# PSUT IoT Engineering Studio | CR73\n",
    "# Demonstrate local KDC session-key wrapping with authenticated encryption.\n",
    "# Classroom-only generated keys; no external service or user credentials.\n",
    "# ------------------------------------------------------------\n",
    "import json\n",
    "import os\n",
    "from cryptography.hazmat.primitives.ciphers.aead import AESGCM\n",
    "from cryptography.exceptions import InvalidTag\n",
    "\n",
    "\n",
    "def demonstrate(now=5, expires=10, revoked=False):\n",
    "    \"\"\"Apply a lifecycle policy before distributing a fresh session key.\"\"\"\n",
    "    if now >= expires or revoked:\n",
    "        return {'issued': False, 'reason': 'expired' if now >= expires else 'revoked'}\n",
    "    # Separate long-term keys model the KDC's independent trust relationships.\n",
    "    alice, bob = (AESGCM(AESGCM.generate_key(bit_length=256)) for _ in range(2))\n",
    "    session = AESGCM.generate_key(bit_length=256)\n",
    "    nonce_a, nonce_b = os.urandom(12), os.urandom(12)\n",
    "    aad_a, aad_b = b'PSUT-CR73|Alice', b'PSUT-CR73|Bob'\n",
    "    wrapped_a = alice.encrypt(nonce_a, session, aad_a)\n",
    "    wrapped_b = bob.encrypt(nonce_b, session, aad_b)\n",
    "    shared = alice.decrypt(nonce_a, wrapped_a, aad_a) == bob.decrypt(nonce_b, wrapped_b, aad_b)\n",
    "    # A changed authenticated ciphertext must never yield usable key material.\n",
    "    altered = bytearray(wrapped_a)\n",
    "    altered[-1] ^= 1\n",
    "    rejected = False\n",
    "    try:\n",
    "        alice.decrypt(nonce_a, bytes(altered), aad_a)\n",
    "    except InvalidTag:\n",
    "        rejected = True\n",
    "    assert shared and rejected\n",
    "    return {'issued': True, 'wrapped_bytes': len(wrapped_a), 'same_session_key': shared, 'altered_tag_rejected': rejected}\n",
    "\n",
    "\n",
    "# Execute the extended practical directly in the notebook.\n",
    "print(json.dumps({\"baseline\": demonstrate(), \"expired\": demonstrate(11), \"revoked\": demonstrate(revoked=True)}, indent=2))\n"
   ],
   "id": "8ebf479ac8f80618"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
