Created
April 6, 2024 20:49
-
-
Save rubenarakelyan/2ee1746a99487cc2c470e6ceca50e0ce to your computer and use it in GitHub Desktop.
Calculate the CSP hash of a script in the browser console
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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