Generating SHA-256 Hashes
You'll learn how to calculate SHA-256 hashes of your inline scripts and styles so CSP can verify them without using nonces.
The Core Idea
In the previous lesson, you learned that CSP hashes allow you to whitelist specific inline code. Now you need to actually generate those SHA-256 hashes. A SHA-256 hash is a cryptographic fingerprint—a fixed-length string that uniquely represents your exact code content. Change even one character, and the hash changes completely.
Think of it like a barcode for your code: the browser scans it and says "yes, this exact script is allowed."
How to Calculate SHA-256 Hashes
Using Browser DevTools
The easiest method: let the browser tell you! When CSP blocks an inline script, the console error message includes the hash you need:
Refused to execute inline script because it violates CSP directive.
Either the 'unsafe-inline' keyword, a hash ('sha256-abc123...'), or a nonce is required.
Using OpenSSL (Command Line)
For a more direct approach, use the OpenSSL command:
echo -n "console.log('Hello');" | openssl dgst -sha256 -binary | openssl base64
This outputs: sha256-hwuHNfAy1w77OQx9Kg5KkFOXovgeXsMlWZZSPvGPcJI=
Using Online Tools
Many websites offer SHA-256 hash generators where you paste your code and get the hash instantly. Just ensure you're using the exact code as it appears in your HTML, including whitespace.
Important Details
The hash must match exactly: spaces, line breaks, and every character count. Hash the code between the tags, not including the <script> or <style> tags themselves.
Key Takeaway: Generate SHA-256 hashes using browser errors, command-line tools, or online generators to create precise fingerprints of your inline code for CSP whitelisting.