How-ToAbout

Content Security Policy (CSP)

Generate Hash for Internal Scripts and Styles

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.

CSP Hash via PowerShell

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

Function Get-CspSha256Hash { [CmdletBinding()] param( [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [System.String] #Text to hash $Text ) $CSP = New-Object System.Security.Cryptography.SHA256CryptoServiceProvider $TextBytes = [System.Text.Encoding]::UTF8.GetBytes($Text) $HashBytes = $CSP.ComputeHash($TextBytes) $CSPHash = [System.Convert]::ToBase64String($HashBytes) $Result = 'sha256-{0}' -f $CSPHash return $Result } # End Function Get-CspSha256Hash

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'; } .listed-item { display: flex; justify-content: center; align-items: center; }" 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.