bcrypt 加密

204 阅读1分钟

🔐 什么是 bcrypt ?

bcrypt 是一个专门用来做密码加密的库。
它不是普通的 MD5、SHA1,那些太容易被破解。

bcrypt 最大的特点:

不可逆(无法解密)
自带随机盐(salt) ,每次生成的密文都不同
安全性非常高
适合密码存储
✔ 被业界大量使用(GitHub / Heroku / MongoDB / PHP 都在用)


🧠 bcrypt 的核心原理(很简单)

当你存密码,比如 123456 时,bcrypt 不会直接保存这个密码。

流程如下:

  1. 生成一个随机 salt(盐)
  2. 用你的密码 + 盐 做多轮哈希处理(默认 10 轮)
  3. 最后得到一个完全不同的加密字符串

✔ 即使两个用户密码一样,加密结果也完全不同。
✔ “加密后不能反向解密”,只能对比。


🧪 bcrypt 的两个核心 API

1. 哈希加密:hash()

把密码转成安全的密文。

import * as bcrypt from 'bcrypt';

const saltRounds = 10;
const hash = await bcrypt.hash("123456", saltRounds);
console.log(hash);

输出类似:

$2b$10$yYHDGSCim30POqPxlHOK7OyM2bEPB0l/wA2VY0p3GG9AaJfV9jLGM

注意:
👉 每次 hash() 的结果都不同,但这不会影响验证。


2. 密码校验:compare()

登录时用户输入密码时做校验。

const isMatch = await bcrypt.compare("123456", hash);
console.log(isMatch); // truefalse

compare() 会自动处理盐,不需要你自己做。


📦 bcrypt 在 NestJS 中怎么用?


1)安装(正确写法)

npm install bcrypt
npm install -D @types/bcrypt

2)注册时加密

import * as bcrypt from 'bcrypt';

async register(dto) {
  const saltRounds = 10;
  const hash = await bcrypt.hash(dto.password, saltRounds);

  await this.userRepo.save({
    username: dto.username,
    password: hash
  });
}

3)登录时验证密码

async login(dto) {
  const user = await this.userRepo.findOne({ where: { username: dto.username } });

  if (!user) throw new Error('用户不存在');

  const isMatch = await bcrypt.compare(dto.password, user.password);

  if (!isMatch) throw new Error('密码错误');

  return user;
}