{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "e3a4780a",
   "metadata": {},
   "source": [
    "# CR78 · TLS 1.3 handshake and encrypted records\n",
    "\n",
    "TLS 1.3 negotiates supported versions and key shares in hello messages, derives handshake keys, encrypts later handshake messages, and uses AEAD. Compatibility CCS is not a key-transition signal as in TLS 1.2.\n",
    "\n",
    "Foundational concepts; prerequisite: CR77.\n",
    "\n",
    "**Scope:** Full-handshake state model (no PSK, HRR, mTLS or resumption)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "id": "concept078",
   "source": [
    "## TLS 1.3 handshake\n",
    "\n",
    "TLS 1.3 separates cipher suite selection from key exchange/signature algorithms. It encrypts authentication messages after ServerHello under handshake traffic keys.\n",
    "\n",
    "**Mathematical / protocol foundations:** ClientHello includes supported versions and usually key_share; ServerHello selects parameters/share. HKDF key schedule derives handshake traffic keys; EncryptedExtensions, Certificate, CertificateVerify and Finished are protected. Client Finished precedes ordinary application-data exchange.\n",
    "\n",
    "**Worked teaching example and interpretation:** Ephemeral DH can provide forward secrecy: later compromise of long-term signing key does not alone reveal recorded sessions if ephemeral secrets are erased. 0-RTT has replay limitations; the modeled full handshake excludes it.\n",
    "\n",
    "Compare corresponding states; for randomized or timed runs compare invariants rather than literal random bytes or timings.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "network78",
   "metadata": {},
   "source": [
    "## TLS 1.3 transcript verification\n",
    "\n",
    "ServerHello completes negotiation of the key share; HKDF derives handshake traffic secrets. EncryptedExtensions, Certificate, CertificateVerify and Finished follow under handshake protection. CertificateVerify signs the transcript; Finished authenticates it under a derived key. Full handshake only; no PSK, resumption or 0-RTT."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "608f7650",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR78 | Live algorithm and verification =====\n",
    "# The function returns actual modeled intermediate states and checks the result.\n",
    "# ------------------------------------------------------------\n",
    "# PSUT IoT Engineering Studio | CR78\n",
    "# Experiment: tls 1 3 handshake and encrypted records\n",
    "# Purpose: expose algorithm states and verify the experiment invariant.\n",
    "# ------------------------------------------------------------\n",
    "# CR78 | TLS 1.3 handshake and encrypted records\n",
    "# Execute the named operation; expose states and assert the laboratory invariant.\n",
    "import json\n",
    "\n",
    "\n",
    "\n",
    "DEFAULT={'certificate_valid': True, 'finished_valid': True}\n",
    "ALTERNATE={'finished_valid': False}\n",
    "\n",
    "def run(overrides=None):\n",
    "    # Merge only explicitly supplied inputs with the lecture baseline.\n",
    "    params={**DEFAULT, **(overrides or {})}\n",
    "    certificate_valid=params['certificate_valid']\n",
    "    finished_valid=params['finished_valid']\n",
    "    if type(certificate_valid) is not bool or type(finished_valid) is not bool:\n",
    "        raise ValueError('Invalid classroom input')\n",
    "    steps=[{'from':'Client','to':'Server','message':'ClientHello: supported_versions, key_share'},{'from':'Server','to':'Client','message':'ServerHello: selected key_share'},{'state':'derive handshake traffic secrets using HKDF'},{'from':'Server','to':'Client','message':'EncryptedExtensions, Certificate, CertificateVerify, Finished','encrypted':True},{'state':'verify identity and Finished','certificate':certificate_valid,'finished':finished_valid}];accept=certificate_valid and finished_valid\n",
    "    if accept:steps += [{'from':'Client','to':'Server','message':'Finished','encrypted':True},{'state':'derive application traffic keys; send encrypted data'}]\n",
    "    else:steps.append({'state':'abort'})\n",
    "    result={'application_allowed':accept}\n",
    "    # Independently check the stated mathematical or protocol invariant.\n",
    "    assert result[\"application_allowed\"]==(certificate_valid and finished_valid), \"verification failed\"\n",
    "    return {\"steps\":steps,\"result\":result}\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "01d4d706",
   "metadata": {},
   "source": [
    "## Baseline calculation\n",
    "Inspect each trace row. The final result is separate from intermediate states."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2576e856",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR78 | 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": "f3e8a436",
   "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": "e94d73fd",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR78 | 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": "dca91b6c",
   "metadata": {},
   "source": [
    "## Controlled investigation\n",
    "\n",
    "Run all four combinations of certificate_valid and finished_valid. Create a four-row table of identity decision, transcript decision and application permission. Locate the first encrypted handshake flight and compare with CR77.\n",
    "\n",
    "ServerHello completes negotiation of the key share; HKDF derives handshake traffic secrets. EncryptedExtensions, Certificate, CertificateVerify and Finished follow under handshake protection. CertificateVerify signs the transcript; Finished authenticates it under a derived key. Full handshake only; no PSK, resumption or 0-RTT."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}