Node.js 》》bcryptjs 加密

发布于:2025-08-09 ⋅ 阅读:(16) ⋅ 点赞:(0)

bcryptjs

# 安装
         npm install bcryptjs


# 基本用法 
  #1. 同步哈希和验证
	const bcrypt = require('bcryptjs');
	// 哈希密码
	const salt = bcrypt.genSaltSync(10); // 生成盐,10是成本因子
	const hashedPassword = bcrypt.hashSync('myPassword123', salt);
	
	console.log('Hashed Password:', hashedPassword);
	
	// 验证密码
	const isValid = bcrypt.compareSync('myPassword123', hashedPassword);
	console.log('Password valid:', isValid); // true
	
	const isInvalid = bcrypt.compareSync('wrongPassword', hashedPassword);
	console.log('Password valid:', isInvalid); // false
# 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); // true
	
	    const isInvalid = await bcrypt.compare('wrongPassword', hashedPassword);
	    console.log('Password valid:', isInvalid); // false
	  } 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}`);
});

网站公告

今日签到

点亮在社区的每一天
去签到