CSP Hash Generator
When I need a CSP Hash?
If you are already implemented the Content-Security-Policy header and want to use inline scripts and/or styles but don't want to use the 'unsafe-inline' directive. Then probably you will see a similar error in DevTools console.
What's a CSP Hash?
It's a string composed of two parts connected by a dash with each other - the cryptographic algorithm used to create the hash value (message digest) and base64-encoded hash of a script or style.
How to generate a CSP Hash?
To generate a CSP hash with PHP use the following code snippet:
$algo = 'sha256';
$data = "console.log('Hello World');"; # This is your inline JS/CSS without the <script>/<style> tags
$data = preg_replace('/\r\n/', '\n', $data);
$base64 = base64_encode(hash($algo, $data, true));
Where to use CSP hashes?
Append this hash to the script-src or style-src
directives of your
Content-Security-Policy header. This is how to send
an HTTP response header:
- CSP header with Apache:
Header set Content-Security-Policy "script-src 'sha256-4saCEHt0PuLiuYPF+oVKJcY5vrrl+WqXYIoq3HAH4vg='"
- CSP header with PHP:
header("Content-Security-Policy: script-src 'sha256-4saCEHt0PuLiuYPF+oVKJcY5vrrl+WqXYIoq3HAH4vg='");
Share this tool with friends and colleagues on your favorite social network: