js实现hash
实现哈希函数的方法
在JavaScript中,可以通过多种方式实现哈希功能,以下是常见的几种方法:
使用内置的crypto模块(Node.js环境)

const crypto = require('crypto');
function hashString(str, algorithm = 'sha256') {
return crypto.createHash(algorithm).update(str).digest('hex');
}
使用Web Crypto API(浏览器环境)
async function hashString(str, algorithm = 'SHA-256') {
const encoder = new TextEncoder();
const data = encoder.encode(str);
const hashBuffer = await crypto.subtle.digest(algorithm, data);
return Array.from(new Uint8Array(hashBuffer))
.map(b => b.toString(16).padStart(2, '0'))
.join('');
}
简单哈希函数实现(适用于小型项目)

function simpleHash(str) {
let hash = 0;
for (let i = 0; i < str.length; i++) {
const char = str.charCodeAt(i);
hash = (hash << 5) - hash + char;
hash |= 0; // 转换为32位整数
}
return hash.toString(16);
}
注意事项
安全哈希算法(如SHA系列)更适合密码学场景,而简单哈希函数仅适用于非安全性要求的场景如哈希表实现。
Web Crypto API仅在安全上下文(HTTPS或localhost)中可用,在普通HTTP页面可能无法工作。
对于密码存储,应该使用专门的密码哈希函数如bcrypt、PBKDF2或Argon2,而不是普通哈希函数。






