如何使用Javascript生成经Base64编码的SHA256哈希字符串?
用JavaScript实现CSP脚本哈希生成
以下实现和你给出的Python代码逻辑完全对齐,最终输出的哈希值完全一致:
Node.js 环境实现
const crypto = require('crypto'); // 字符串内容要和实际脚本完全一致,包括换行、缩进、特殊字符 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(); } } //]]> `; // 执行逻辑:UTF-8编码 → SHA256哈希 → Base64编码 const hash = crypto.createHash('sha256').update(string, 'utf8').digest('base64'); const cspHash = `sha256-${hash}`; console.log(cspHash);
浏览器端实现(基于Web Crypto API)
async function generateCSPHash(str) { // 转换为UTF-8编码的字节流 const encoder = new TextEncoder(); const data = encoder.encode(str); // 计算SHA256哈希 const hashBuffer = await crypto.subtle.digest('SHA-256', data); // 转换为Base64格式 const hashArray = Array.from(new Uint8Array(hashBuffer)); const hashBase64 = btoa(String.fromCharCode(...hashArray)); return `sha256-${hashBase64}`; } // 调用示例 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(); } } //]]> `; generateCSPHash(string).then(console.log);
注意:输入字符串的所有字符(包括换行、缩进、空格、特殊符号)必须和实际要加载的脚本完全一致,任意字符差异都会导致哈希不匹配,CSP校验失败。
内容的提问来源于stack exchange,提问作者cmdln
相关产品推荐
相关产品推荐

