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;
}
相关推荐
MM_MS21 小时前
Halcon基础知识点及其算子用法
开发语言·人工智能·python·算法·计算机视觉·视觉检测
大厂技术总监下海21 小时前
数据湖加速、实时数仓、统一查询层:Apache Doris 如何成为现代数据架构的“高性能中枢”?
大数据·数据库·算法·apache
hetao17338371 天前
2026-01-06 hetao1733837 的刷题笔记
c++·笔记·算法
a努力。1 天前
国家电网Java面试被问:最小生成树的Kruskal和Prim算法
java·后端·算法·postgresql·面试·linq
洛生&1 天前
Counting Towers
算法
Evand J1 天前
【MATLAB例程,附代码下载链接】基于累积概率的三维轨迹,概率计算与定位,由轨迹匹配和滤波带来高精度位置,带测试结果演示
开发语言·算法·matlab·csdn·轨迹匹配·候选轨迹·完整代码
X在敲AI代码1 天前
LeetCode 基础刷题D2
算法·leetcode·职场和发展
源代码•宸1 天前
Leetcode—1929. 数组串联&&Q1. 数组串联【简单】
经验分享·后端·算法·leetcode·go
数据大魔方1 天前
【期货量化实战】跨期套利策略:价差交易完整指南(TqSdk源码详解)
数据库·python·算法·github·程序员创富
weixin_461769401 天前
15. 三数之和
c++·算法·leetcode·三数之和