Skip to content

Instantly share code, notes, and snippets.

@rubenarakelyan
Created April 6, 2024 20:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rubenarakelyan/2ee1746a99487cc2c470e6ceca50e0ce to your computer and use it in GitHub Desktop.
Save rubenarakelyan/2ee1746a99487cc2c470e6ceca50e0ce to your computer and use it in GitHub Desktop.
Calculate the CSP hash of a script in the browser console
const scripts = document.getElementsByTagName("script"),
script_content = scripts[scripts.length - 1].innerHTML,
enc = new TextEncoder(),
data = enc.encode(script_content);
crypto.subtle.digest('SHA-256', data).then(function(val) {
const digest = ["sha256", _arrayBufferToBase64(val)].join("-");
console.log(`The digest for your script is: ${digest}`);
});
function _arrayBufferToBase64(buffer) {
var binary = "";
var bytes = new Uint8Array(buffer);
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return window.btoa(binary);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment