Image by Pexels from Pixabay

Content Security Policy (CSP) Generate Hash for Internal Scripts & Styles

phbits

--

Content Security Policy (CSP) is an HTTP response header used to protect the client against XSS, clickjacking, and loading untrusted content. When a page has internal scripts or styles, CSP can allow it by using a nonce or specifying it’s hash as a base64 encoded value. This post will show how to determine the value to be placed into the CSP.

For more information about the Content Security Policy specification see:

Content Security Policy Level 2 — W3C Recommendation, 15 December 2016

CSP Hash via PowerShell

The following PowerShell function can be used to calculate the SHA256 hash. Note, the CSP standard supports: SHA256, SHA384, SHA512

https://gist.github.com/phbits/ee9da83c7d826ecef4faad8e459d7485

Set the contents of the <style> tag to a variable, leaving out the actual html tags. Then pass that variable to Get-CspSha256Hash.

$Style = "html, body { height: 100%; font-family: 'Courier'; }"
Get-CspSha256Hash $Style

The returned value can be used for your CSP.

CSP Hash via Console

Perhaps the easiest way to calculate the hash of internal scripts or styles is to let the browser do it! All errors are logged to the browser console (browser developer tools). Below is an example.

Refused to apply inline style because it violates the following Content Security  Policy directive: "style-src 'self' 'sha256-AAAAAAAA...'". Either the  'unsafe-inline' keyword, a hash ('sha256-BBBBBBBB...'), or a nonce  ('nonce=...') is required to enable inline execution.

In the above example, the browser calculated the hash as sha256-BBBBBBBB.... Making it an easy copy/paste into the actual CSP directive.

--

--