{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "c916a9fd",
   "metadata": {},
   "source": [
    "# CR70 · Digital signatures: ECDSA file verification\n",
    "\n",
    "A digital signature binds a digest to a private signing key; a trusted public key verifies it. This lab uses P-256 ECDSA with SHA-256 from a vetted library. Signatures contain r and s; Python uses ASN.1 DER while Web Crypto returns raw r||s. Validity depends on trusted keys, not simply the presence of a signature.\n",
    "\n",
    "## Worked calculation\n",
    "An original synthetic firmware message verifies with its own public key. A modified message and a different public key must be rejected. Signature bytes can vary between runs.\n",
    "\n",
    "## Baseline\n",
    "Sign firmware-v1, verify it, then test an appended exclamation mark and an unrelated public key.\n",
    "\n",
    "## Controlled investigation\n",
    "Repeat for firmware-v2 and empty input. Use fresh keys per run; compare outcomes rather than signature bytes.\n",
    "\n",
    "**Evidence:** Digest, encoding, signature length, original verification, modified-message and wrong-key rejection.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "id": "concept070",
   "source": [
    "## ECDSA signing and verification\n",
    "\n",
    "A signature binds a message to a private signing key, verified by a trusted public key. Non-repudiation depends on key management, identity and evidence, not mathematics alone.\n",
    "\n",
    "**Mathematical / protocol foundations:** For group order n, r=x(kG) mod n, s=k⁻¹(z+rd) mod n. Verify using w=s⁻¹,u1=zw,u2=rw modulo n and compare x(u1G+u2Q) mod n to r; reject invalid ranges/points.\n",
    "\n",
    "**Worked teaching example and interpretation:** The original message verifies; changing message or public key must fail. Use approved library randomness or deterministic signing; nonce misuse can compromise keys. Signatures do not encrypt the message.\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": "af7ef02e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR70 | Dependency check =====\n",
    "# ===== Dependency check =====\n",
    "# Colab normally includes cryptography; install a compatible version if absent.\n",
    "import importlib.util\n",
    "if importlib.util.find_spec(\"cryptography\") is None:\n",
    "    import subprocess,sys\n",
    "    subprocess.check_call([sys.executable,\"-m\",\"pip\",\"install\",\"cryptography>=42\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "af9f58d8",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR70 | Educational algorithm and validation =====\n",
    "# CR70 | Digital signatures: ECDSA file verification\n",
    "# Execute the named operation; expose states and assert the laboratory invariant.\n",
    "import hashlib\n",
    "import json\n",
    "\n",
    "def reject(fn):\n",
    "    try: fn()\n",
    "    except Exception:return True\n",
    "    return False\n",
    "\n",
    "DEFAULT={'message': 'firmware-v1'}\n",
    "ALTERNATE={'message': 'firmware-v2'}\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",
    "    from cryptography.hazmat.primitives.asymmetric import ec\n",
    "    from cryptography.hazmat.primitives.asymmetric.utils import decode_dss_signature\n",
    "    from cryptography.hazmat.primitives import hashes\n",
    "    m=message.encode();key=ec.generate_private_key(ec.SECP256R1());pub=key.public_key();sig=key.sign(m,ec.ECDSA(hashes.SHA256()));r,s=decode_dss_signature(sig);pub.verify(sig,m,ec.ECDSA(hashes.SHA256()));other=ec.generate_private_key(ec.SECP256R1()).public_key()\n",
    "    steps=[{'digest':hashlib.sha256(m).hexdigest()},{'signature_bytes':len(sig),'r_bits':r.bit_length(),'s_bits':s.bit_length(),'encoding':'ASN.1 DER'},{'verification':'accepted'}];result={'tampered_rejected':reject(lambda:pub.verify(sig,m+b'!',ec.ECDSA(hashes.SHA256()))),'wrong_key_rejected':reject(lambda:other.verify(sig,m,ec.ECDSA(hashes.SHA256())))}\n",
    "    # Independently check the stated mathematical or protocol invariant.\n",
    "    assert all(result.values()), \"verification failed\"\n",
    "    return {\"steps\":steps,\"result\":result}\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d7592ddb",
   "metadata": {},
   "source": [
    "## Baseline calculation\n",
    "Inspect each trace row. The final result is separate from intermediate states."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e8702619",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR70 | 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": "83ea2dff",
   "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": "024a26ee",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR70 | 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": [
    "# ===== CR70 | Controlled trials =====\n",
    "# Reinitialize defaults on every run. Record actual traces and compare invariants.\n",
    "for settings in [{'message': ''}]:\n",
    "    trial = run(settings)\n",
    "    print(settings, trial[\"result\"])\n",
    "    for state in trial[\"steps\"]: print(state)\n"
   ],
   "id": "45eb0cf4dc7c8996"
  },
  {
   "cell_type": "markdown",
   "id": "38fd9eab",
   "metadata": {},
   "source": [
    "## Student activity\n",
    "Repeat for firmware-v2 and empty input. Use fresh keys per run; compare outcomes rather than signature bytes.\n",
    "\n",
    "Submit Digest, encoding, signature length, original verification, modified-message and wrong-key rejection.\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
