Tag Archives: csp

Hashes and Nonces in CSP

Troy Hunt has a nice article about inline-scripts and CSP with some practical examples.

By default the following CSP directive will block all inline scripts:

Content-Security-Policy: default-src 'self'

The most straight-forward way to remove the restriction is to add unsafe-inline but it disables all the defenses against inline scripts and XSS. Thankfully you have two alternatives: using a hash or a nonce. (TIL!)

If the script is static (the content does not change), you can add a SHA-256 hash of the script to the CSP directive, so the script will be whitelisted.

Content-Security-Policy: default-src 'self'; script-src 'sha256-blLDIhKaPEZDhc4WD45BC7pZxW4WBRp7E5Ne1wC/vdw='

However, if the script is prone to change, you have the option of adding a base64-encoded nonce (random value) to both the CSP directive and the script tag.

Content-Security-Policy: default-src 'self'; script-src 'nonce-4AEemGb0xJptoIGFP3Nd'
<script type="text/javascript" nonce="4AEemGb0xJptoIGFP3Nd">