bcrypt 加密

🔐 什么是 bcrypt ?

bcrypt 是一个专门用来做密码加密的库。

它不是普通的 MD5、SHA1,那些太容易被破解。

bcrypt 最大的特点:

不可逆(无法解密)

自带随机盐(salt) ,每次生成的密文都不同

安全性非常高

适合密码存储

✔ 被业界大量使用(GitHub / Heroku / MongoDB / PHP 都在用)


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

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

流程如下:

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

✔ 即使两个用户密码一样,加密结果也完全不同。

✔ "加密后不能反向解密",只能对比。


🧪 bcrypt 的两个核心 API

1. 哈希加密:hash()

把密码转成安全的密文。

ini 复制代码
import * as bcrypt from 'bcrypt';

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

输出类似:

perl 复制代码
$2b$10$yYHDGSCim30POqPxlHOK7OyM2bEPB0l/wA2VY0p3GG9AaJfV9jLGM

注意:

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


2. 密码校验:compare()

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

vbnet 复制代码
const isMatch = await bcrypt.compare("123456", hash);
console.log(isMatch); // true 或 false

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


📦 bcrypt 在 NestJS 中怎么用?


1)安装(正确写法)

bash 复制代码
npm install bcrypt
npm install -D @types/bcrypt

2)注册时加密

javascript 复制代码
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)登录时验证密码

javascript 复制代码
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;
}
相关推荐
cjp5606 分钟前
009.UG二次开发,任务环境草图优化3(高级功能生成直线)
算法
样例过了就是过了18 分钟前
LeetCode热题100 分割等和子集
数据结构·c++·算法·leetcode·动态规划
逻辑驱动的ken20 分钟前
Java高频面试考点18
java·开发语言·数据库·算法·面试·职场和发展·哈希算法
北顾笙9801 小时前
day38-数据结构力扣
数据结构·算法·leetcode
m0_629494731 小时前
LeetCode 热题 100-----14.合并区间
数据结构·算法·leetcode
xin_nai1 小时前
LeetCode热题100(Java)(5)普通数组
算法·leetcode·职场和发展
旖-旎1 小时前
深搜练习(组合)(5)
c++·算法·深度优先·力扣
@小码农1 小时前
2026年3月Scratch图形化编程等级考试一级真题试卷
开发语言·数据结构·c++·算法
Wect2 小时前
LeetCode 5. 最长回文子串:DP + 中心扩展
前端·算法·typescript
糖果店的幽灵2 小时前
决策树详解与sklearn实战
算法·决策树·sklearn