Chapter 66: Content Security Policy (CSP)

Cryptographic Hashes in Content Security Policy

**Part 14: Security & Best Practices** — Chapter 66: Content Security Policy (CSP)

LEARNING OBJECTIVES
  • Understand how cryptographic hashes ('sha256-...', 'sha384-...', 'sha512-...') authorize inline <script> and <style> blocks.
  • Calculate Base64 SHA-256 digests of inline script contents using OpenSSL and browser DevTools.
  • Differentiate between CSP nonces (per-request dynamic) and hashes (static immutable).
  • Authorize inline event handlers and external script hashes via CSP Level 3.
🎬 INTERACTIVE VISUAL PIPELINE Core Architecture Simulation
🌐
1. Input
Directives & Tags
⚙️
2. Parse
Tokenizer & AST
🌳
3. Layout
Box Model & Flow
🎨
4. Render
GPU Paint & Composite
PHASE 1: INPUT & DIRECTIVES
Browser receives declarative markup stream, parsing tag tokens and initializing component state.

📖 The Mental Model & Story

Imagine a museum security guard standing in front of a priceless painting. Instead of checking the author's badge every time (like a nonce), the guard takes a high-resolution digital fingerprint of the painting itself.

If anyone changes even a single brushstroke or space character in the code, the hash fingerprint changes completely, and the museum guard blocks execution immediately!

Inline Script Content:
  console.log("Analytics Initialized");

SHA-256 Fingerprint:
  'sha256-wF+l212q4c0q...'

CSP Header:
  Content-Security-Policy: script-src 'self' 'sha256-wF+l212q4c0q...';

📌 Key Takeaways

  • Hashes allow static, immutable inline scripts to run without enabling dangerous 'unsafe-inline'.
  • Any whitespace or comment change inside the <script> tag invalidates the hash and blocks execution.
  • --

❓ Knowledge Check

1. Which of the following is correct?

2. Which of the following is correct?