JS 里使用 SHA256

lishihuan大约 1 分钟

JS 里使用 SHA256

在 JS 里使用 SHA256 有几种方式,主要分为 Web Crypto API(原生)第三方库 两类。


1. 原生方式 【不推荐】

JS 提供了 SubtleCrypto(Web Crypto API):

async function sha256(message) {
  const encoder = new TextEncoder()
  const data = encoder.encode(message)
  const hashBuffer = await crypto.subtle.digest('SHA-256', data)
  const hashArray = Array.from(new Uint8Array(hashBuffer))
  const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('')
  return hashHex
}

// 使用
sha256("hello world").then(console.log)
// 输出: b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9

限制:

  • 必须在安全上下文(secure context)运行 👉 也就是 HTTPS 或者 localhost,否则 crypto.subtleundefined。 因为这是加密 API,浏览器只允许在安全环境里用。
  • 不支持 同步 调用,都是异步 Promise。
  • 兼容性:现代浏览器(Chrome 37+,Firefox 34+,Edge,Safari 11+)基本都支持。

2. 第三方库(无需 HTTPS 限制)

如果你的环境不满足 HTTPS/localhost,可以直接用 JS 实现的库。常见的有:

这些库都是纯 JS 实现,没有 HTTPS 限制,能在任何环境(甚至 file:// 或 HTTP)下使用。


3. Node.js 环境

如果是 Node.js,直接用内置 crypto 模块即可:

const crypto = require("crypto")
const hash = crypto.createHash("sha256").update("hello world").digest("hex")
console.log(hash)

✅ 总结:

  • Web 项目(安全环境)crypto.subtle.digest(浏览器原生,性能最好)。
  • Web 项目(非 HTTPS / 内网调试)crypto-js / js-sha256
  • Node.js → 内置 crypto 模块