Hash-Based Style Whitelisting
What you'll learn: How to compute SHA hashes for specific inline styles and whitelist them in your Content Security Policy without weakening your entire style-src directive.
The Core Idea
Hash-based style whitelisting allows you to permit specific inline <style> blocks or style attributes by computing their SHA-256 (or SHA-384/SHA-512) hash and adding it to your CSP header. This is similar to hash-based script whitelisting, but applied to CSS. Instead of using 'unsafe-inline' (which opens the door to all injected styles) or managing dynamic nonces, you calculate a cryptographic hash of your static inline style content and explicitly authorize just that exact style.
How It Works
When the browser encounters inline CSS, it computes the hash of that content. If the hash matches one listed in your style-src directive, the style is applied. If not, it's blocked.
Example:
Suppose you have this inline style:
<style>body { background: blue; }</style>
You'd compute its SHA-256 hash (the content between the tags, including whitespace):
sha256-xyz123abc... (example hash)
Then add it to your CSP header:
Content-Security-Policy: style-src 'self' 'sha256-xyz123abc...'
Now only that exact style block will execute. Any injected styles with different content will be blocked.
Why Use Hashes for Styles?
Hash-based whitelisting gives you pinpoint control over inline styles without requiring server-side nonce generation. It's perfect for static inline styles that don't change between requests, like critical CSS inlined for performance.
Key Takeaway: Hash-based style whitelisting lets you approve specific inline styles by their cryptographic fingerprint, maintaining strong CSP protection while allowing necessary inline CSS without 'unsafe-inline' or nonce infrastructure.