Cryptography guides

Match a CSP hash to the exact inline content

·

A content security policy can authorize an inline script or stylesheet by its hash. Start with the exact text of the trusted element so you can tell when formatting changes require a new source.

CSP Nonce and Hash Generator

Hash a one-line stylesheet

Select Load example, then Generate hashes. The source contains 31 UTF-8 bytes and the directive is style-src. Compare the SHA-256 line with the example below. The three output lines show alternative algorithms for the same contents.

For an actual page, put the matching quoted source in your existing policy's applicable style directive. Copy the inline text between the element tags, including any formatting whitespace the page serves.

Inline CSS and the corresponding SHA-256 directive example
.site-title { color: #294c39; }

W3C Content Security Policy Level 3

Test what changes when you reformat the markup

Add one newline after the closing brace and generate again. The count rises to 32 and all three expressions change. A line break added before the closing style tag is part of the element text.

Pasted text follows browser text-field line breaks. The Exact file bytes option preserves every byte, including CRLF or a byte-order mark. When hashing a source for an HTML inline element, compare its parsed text because HTML normalizes line endings during parsing.

W3C Content Security Policy Level 3WHATWG HTML input-stream preprocessing

Match a nonce source and element attribute

Switch Generate to Fresh nonce. The quoted source is suitable for the applicable script or style directive. The matching nonce attribute belongs on the trusted element in that same response.

Generate again to see a different 128-bit token. A deployed site should generate the nonce as part of serving each response and use that response's token in both policy and markup.

W3C Content Security Policy Level 3

Common questions

Do I add all three algorithm lines?

Each line is an alternative directive example. Select an appropriate matching source and incorporate it into your existing policy.

Does an exact file hash always match served inline content?

Only when the bytes match the UTF-8 form of the inline text the browser uses. Parsing and template formatting can change line endings or whitespace.

Sources

Put it into practice.

Related guides