Content Security Policy (CSP)
Quick Reference Guide


Using a hash with CSP

A hash of a script or style can be used to allow it .

CSP Hash Example

Using a hash is one way to allow the execution of inline scripts in a Content Security Policy (CSP). Here's how one might use it with the CSP with JavaScript:

Suppose we have the following script on our page:

<script>doSomething();</script>

If you compute the SHA-256 hash of our entire JavaScript code block, in our case it is just: doSomething(); you will get the value:

RFWPLDbv2BY+rCkDzsE+0fr8ylGr2R2faWMhq4lfEQc=

Finally we can add the hash to our script-src directive to allow it to execute via our Content-Security-Policy header:

script-src 'sha256-RFWPLDbv2BY+rCkDzsE+0fr8ylGr2R2faWMhq4lfEQc=';

What CSP hash algorithms are supported?

The CSP Level 2 specification allows sha256, sha384, and sha512

How do you generate the hash?

The easiest way to generate it is to just open the developer tools console and it will output what the expected hash of your script was in the console error message.

You can also use tools such as openssl to generate it, whitespace is not ignored.

Here is an example using openssl, which will be installed by default on most mac or linux systems:

echo -n 'doSomething();' | openssl sha256 -binary | openssl base64

CSP Hash Browser Support

The hash source list directive was added to CSP Level 2. This means that support has existed since 2015 in Chrome and Firefox, Safari 10+ or Edge 15+.

It is not supported at all in Internet Explorer, you need to use the Edge browser instead.