浏览器中的 SHA-256

用浏览器的 Web Crypto API 计算真实的 SHA-256 摘要。

哈希已知输入

这个完整示例对 UTF-8 文本 abc 做哈希。它只用标准浏览器 API,在本地运行。这只是哈希演示,不是挖矿引擎,也不是正式证明。

JavaScript
const bytes = new TextEncoder().encode('abc');
const digest = await crypto.subtle.digest('SHA-256', bytes);
const hex = Array.from(new Uint8Array(digest), (byte) =>
  byte.toString(16).padStart(2, '0')
).join('');

const expected =
  'ba7816bf8f01cfea414140de5dae2223' +
  'b00361a396177a9cb410ff61f20015ad';
if (hex !== expected) throw new Error('SHA-256 校验失败。');
console.log(hex);

文本与字节不同

摘要取决于确切的字节。文本 2a 是两个 UTF-8 字节,而十六进制字节 0x2a 只有一个字节。文本编码和二进制编码不能互换。

JavaScript
const textBytes = new TextEncoder().encode('2a');
const binaryBytes = new Uint8Array([0x2a]);

console.log(Array.from(textBytes));   // [50, 97]
console.log(Array.from(binaryBytes)); // [42]

读取输出

SHA-256 输出 32 字节。每个字节写成两个十六进制字符,得到 64 个字符的字符串。补零会保留前导零。相同字节总是得到相同摘要。

挖矿请用挖矿台

实际的挖矿台自行管理当前挑战和搜索引擎。这些示例不向挖矿服务发送请求,也不演示开启或完成一轮。