bcryptjs
# 安装
npm install bcryptjs
# 基本用法
#1. 同步哈希和验证
const bcrypt = require('bcryptjs');
const salt = bcrypt.genSaltSync(10);
const hashedPassword = bcrypt.hashSync('myPassword123', salt);
console.log('Hashed Password:', hashedPassword);
const isValid = bcrypt.compareSync('myPassword123', hashedPassword);
console.log('Password valid:', isValid);
const isInvalid = bcrypt.compareSync('wrongPassword', hashedPassword);
console.log('Password valid:', isInvalid);
# 2. 异步哈希和验证(推荐)
const bcrypt = require('bcryptjs');
async function hashAndVerify() {
try {
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash('myPassword123', salt);
console.log('Hashed Password:', hashedPassword);
const isValid = await bcrypt.compare('myPassword123', hashedPassword);
console.log('Password valid:', isValid);
const isInvalid = await bcrypt.compare('wrongPassword', hashedPassword);
console.log('Password valid:', isInvalid);
} catch (err) {
console.error('Error:', err);
}
}
hashAndVerify();
在实际应用中的使用示例
const express = require('express');
const bcrypt = require('bcryptjs');
const app = express();
app.use(express.json());
const users = [];
app.post('/register', async (req, res) => {
try {
const { username, password } = req.body;
const userExists = users.some(user => user.username === username);
if (userExists) {
return res.status(400).json({ message: '用户名已存在' });
}
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(password, salt);
const newUser = {
id: Date.now().toString(),
username,
password: hashedPassword
};
users.push(newUser);
res.status(201).json({ message: '用户注册成功', userId: newUser.id });
} catch (err) {
res.status(500).json({ message: '注册失败', error: err.message });
}
});
app.post('/login', async (req, res) => {
try {
const { username, password } = req.body;
const user = users.find(user => user.username === username);
if (!user) {
return res.status(401).json({ message: '用户名或密码错误' });
}
const isValidPassword = await bcrypt.compare(password, user.password);
if (!isValidPassword) {
return res.status(401).json({ message: '用户名或密码错误' });
}
res.json({ message: '登录成功', userId: user.id });
} catch (err) {
res.status(500).json({ message: '登录失败', error: err.message });
}
});
const PORT = 3000;
app.listen(PORT, () => {
console.log(`服务器运行在 http://localhost:${PORT}`);
});