用 JavaScript 计算 SHA-256 hash值

本文介绍了如何在JavaScript中(特别是浏览器和Node.js环境)使用SHA-256算法生成散列值,包括使用WebCryptoAPI的SubtleCrypto接口以及Node.js内置加密库crypto的示例。
摘要由CSDN通过智能技术生成

SHA-256算法是一个广泛使用的散列函数,它产生256位的hash值。它用于许多安全应用程序和协议,包括 TLS 和 SSL、 SSH、 PGP 和比特币。

在 JavaScript 中计算 SHA-256 hash值使用原生 API 很容易,但是浏览器和 Node.js 之间有一些区别。由于浏览器实现是异步的,所以所提供的两个示例都使用异步promise返回。

浏览器实现

使用 Web Crypto API 中 SubtleCrypto 接口,SubtleCrypto.digest() 接口会返回给定数据的摘要,摘要以ArrayBuffer 的形式返回,需要将其转换为十六进制字符串。

const hashValue = val =>
crypto.subtle
  .digest('SHA-256', new TextEncoder('utf-8').encode(val))
  .then(h => {
    let hexes = [],
      view = new DataView(h);
    for (let i = 0; i < view.byteLength; i += 4)
      hexes.push(('00000000' + view.getUint32(i).toString(16)).slice(-8));
    return hexes.join('');
  });

hashValue(
JSON.stringify({ coder: "fe-garden", subject: 'sha-256', type: { module: "nodejs" } })
).then(console.log);
// '6c0225ba749b8701a5d051d02faafb1fdadc9457a2eaf81bf89e3353a6aaa4f1'

Nodejs实现

使用node 内置的加密库crypto实现。

import { createHash } from "crypto";

const hashValue = (val) =>
new Promise((resolve) => {
  const hash = createHash("sha256").update(val).digest("hex");
  resolve(hash);
});

hashValue(JSON.stringify({ coder: "fe-garden", subject: 'sha-256', type: { module: "nodejs" } })).then(
console.log
);
//6c0225ba749b8701a5d051d02faafb1fdadc9457a2eaf81bf89e3353a6aaa4f1

注意

  • 上述两个实现互不兼容,不能在 Node.js 中使用浏览器实现,反之亦然;

  • 两种实现应该为相同的输入产生相同的结果。

总结

以上就是利用js 实现sha256方法,包括浏览器版本的javascript 使用sha256算法,和Nodejs 中js计算sha256Hex 方法,希望对你有所帮助。

参考资料

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论
HMAC-SHA256是一种哈希算法,它需要密钥和消息输入。在JavaScript中,我们可以使用CryptoJS库来实现HMAC-SHA256。但是,如果您不想使用库,可以尝试以下方法: ```javascript function hmacSHA256(key, message) { const sha256HashLength = 64; // SHA-256 hash length in bytes const blockSize = 512; // HMAC block size in bits const ipad = 0x36; // Inner padding value const opad = 0x5c; // Outer padding value // Convert key and message to byte arrays const keyBytes = new TextEncoder().encode(key); const messageBytes = new TextEncoder().encode(message); // If the key is longer than the block size, hash it first if (keyBytes.length > blockSize / 8) { keyBytes = new Uint8Array(await crypto.subtle.digest('SHA-256', keyBytes)); } // Pad the key with zeros to the block size const paddedKey = new Uint8Array(blockSize / 8); paddedKey.set(keyBytes); paddedKey.forEach((byte, index) => { paddedKey[index] ^= ipad; }); // Concatenate the padded key and message const concatenated = new Uint8Array(paddedKey.length + messageBytes.length); concatenated.set(paddedKey); concatenated.set(messageBytes, paddedKey.length); // Hash the concatenated value const hashed = new Uint8Array(await crypto.subtle.digest('SHA-256', concatenated)); // Pad the outer key with zeros to the block size const outerPaddedKey = new Uint8Array(blockSize / 8); outerPaddedKey.set(keyBytes); outerPaddedKey.forEach((byte, index) => { outerPaddedKey[index] ^= opad; }); // Concatenate the outer padded key and the hashed value const finalConcatenated = new Uint8Array(outerPaddedKey.length + sha256HashLength); finalConcatenated.set(outerPaddedKey); finalConcatenated.set(hashed, outerPaddedKey.length); // Compute the final hash const finalHash = await crypto.subtle.digest('SHA-256', finalConcatenated); // Convert the final hash to a hexadecimal string return Array.from(new Uint8Array(finalHash)) .map((byte) => byte.toString(16).padStart(2, '0')) .join(''); } ``` 上面的函数接受密钥和消息字符串作为输入,并返回一个十六进制字符串,它是HMAC-SHA256哈希。请注意,此函数使用JavaScript的Web Cryptography API来执行哈希计算。如果您需要在旧版浏览器上运行此代码,则需要使用polyfill来支持Web Cryptography API。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端后花园

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值