小编cmd*_*dln的帖子

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

我想记录脚本哈希值以实施内容安全策略。我已经能够使用以下代码在 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'))
Run Code Online (Sandbox Code Playgroud)

我怎样才能用 JavaScript 做到这一点?

javascript python base64 sha256 content-security-policy

4
推荐指数
1
解决办法
3904
查看次数