如何在 Javascript 中创建 Base64 编码 SHA256 字符串?

How to create Base64 encode SHA256 string in Javascript?

我想记录脚本哈希以实施内容安全策略。我已经能够使用以下代码在 python 中生成哈希:

import hashlib
import base64

string='''
//<![CDATA[
var theForm = document.forms['ctl00'];
if (!theForm) {
    theForm = document.ctl00;
}
function __doPostBack(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
        theForm.__EVENTTARGET.value = eventTarget;
        theForm.__EVENTARGUMENT.value = eventArgument;
        theForm.submit();
    }
}
//]]>
'''
# encode as UTF-8
string_UTF8 = string.encode('utf-8')

# hash the message
hash_string = hashlib.sha256(string_UTF8).digest()

# base64 encode
result = base64.b64encode(hash_string)

print('sha256-' + result.decode('utf-8'))

如何使用 Javascript 执行此操作?

我最终使用了这个 JQuery 插件 https://github.com/angeal185/jquery-hash 以下代码得到正确答案:

<script>
  var s = "\n//<![CDATA[\nvar theForm = document.forms['ctl00'];\nif (!theForm) {\n    theForm = document.ctl00;\n}\nfunction __doPostBack(eventTarget, eventArgument) {\n    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {\n        theForm.__EVENTTARGET.value = eventTarget;\n        theForm.__EVENTARGUMENT.value = eventArgument;\n        theForm.submit();\n    }\n}\n//]]>\n"
  $.hash(s, '256', 'base64',function(i){
  console.log(i)
  });
</script>

const string = `
//<![CDATA[
var theForm = document.forms['ctl00'];
if (!theForm) {
    theForm = document.ctl00;
}
function __doPostBack(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
        theForm.__EVENTTARGET.value = eventTarget;
        theForm.__EVENTARGUMENT.value = eventArgument;
        theForm.submit();
    }
}
//]]>
`

async function hashFromString(string) {
    const hash = await crypto.subtle.digest("SHA-256", (new TextEncoder()).encode(string))
    return "sha256-" + btoa(String.fromCharCode(...new Uint8Array(hash)))
}

hashFromString(string).then(console.log)

编辑:我现在意识到虽然您的问题中没有说明,但您可能正在使用 Node.js 因此使用浏览器 API 的这个答案可能用处不大。