Node.js Crypto — 加密与哈希
用 crypto 模块进行数据加密、生成哈希、HMAC 签名 · 难度:进阶 · +20XP
crypto 模块
crypto 提供加密和哈希功能。用户密码存储、数据校验、安全通信都离不开它。
哈希(Hash)— 单向不可逆
用哈希可以把任意长度的数据变成固定长度的"指纹":
const crypto = require("crypto");
// MD5(不安全,别用于密码!)
const md5 = crypto.createHash("md5").update("hello").digest("hex");
console.log(md5); // 5d41402abc4b2a76b9719d911017c592
// SHA256(推荐)
const sha = crypto.createHash("sha256").update("hello").digest("hex");
console.log(sha); // 64位十六进制字符串
密码存储的正确方式:加盐哈希
const crypto = require("crypto");
function hashPassword(password) {
const salt = crypto.randomBytes(16).toString("hex");
const hash = crypto.pbkdf2Sync(password, salt, 100000, 64, "sha512");
return salt + ":" + hash.toString("hex");
}
const hashed = hashPassword("mypassword123");
console.log("存储的密码:", hashed);
回顾:永远不要明文存密码!用 SPA 前端学习时你可能在 localStorage 存过 token,后端存密码必须用哈希。