Skip to content

Instantly share code, notes, and snippets.

@rubenarakelyan
Created April 6, 2024 20:49
Show Gist options
  • Select an option

  • Save rubenarakelyan/2ee1746a99487cc2c470e6ceca50e0ce to your computer and use it in GitHub Desktop.

Select an option

Save rubenarakelyan/2ee1746a99487cc2c470e6ceca50e0ce to your computer and use it in GitHub Desktop.

Revisions

  1. rubenarakelyan created this gist Apr 6, 2024.
    19 changes: 19 additions & 0 deletions csp-hash.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,19 @@
    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);
    }