You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中对字符串哈希?寻求现成可靠实现方案

字符串哈希的现成实现方案

一、浏览器内置:Web Crypto API

这是浏览器原生提供的安全加密API,无需额外依赖,可靠性高。示例代码如下:

async function hashString(str) {
  const encoder = new TextEncoder();
  const data = encoder.encode(str);
  const hashBuffer = await crypto.subtle.digest('SHA-256', data);
  // 将ArrayBuffer转换为十六进制字符串
  const hashArray = Array.from(new Uint8Array(hashBuffer));
  const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
  return hashHex;
}

// 使用示例
const string = "password";
hashString(string).then(hash => {
  console.log(hash); // 输出 5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8
});

说明:该API为异步调用,支持SHA-1、SHA-256、SHA-384、SHA-512等多种哈希算法,替换digest方法的第一个参数即可切换。

二、Node.js内置:crypto模块

Node.js自带的crypto模块,无需安装依赖,适合后端场景:

const crypto = require('crypto');

function hashString(str) {
  return crypto.createHash('sha256').update(str).digest('hex');
}

// 使用示例
const string = "password";
const hash = hashString(string);
console.log(hash); // 输出 5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8

说明:同步调用即可完成哈希计算,支持多种算法,修改createHash的参数可切换哈希类型。

三、可靠npm包:crypto-js

若需兼容旧环境(如不支持Web Crypto的老浏览器),可使用成熟的crypto-js包:

  1. 先安装依赖:
npm install crypto-js
  1. 使用示例:
const CryptoJS = require('crypto-js');

function hashString(str) {
  return CryptoJS.SHA256(str).toString(CryptoJS.enc.Hex);
}

// 使用示例
const string = "password";
const hash = hashString(string);
console.log(hash); // 输出 5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8

说明:该包支持多种哈希与加密算法,文档完善,社区维护活跃。

内容的提问来源于stack exchange,提问作者Rolazar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 10:05:31