Nodejs 使用 bcrypt 库加密和验证密码
2023-09-14 08:58:44 时间
install
λ npm i bcrypt
λ npm i --save-dev @types/bcrypt
example
import * as bcrypt from 'bcrypt';
const db = {}
(async () => {
const myPlaintextPassword = 'hello world'; // 我的明文密码
const someOtherPlaintextPassword = 'not_bacon'; // 错误的密码
// 注册
await register('ajanuw', myPlaintextPassword);
// 登录
login('ajanuw', myPlaintextPassword);
login('ajanuw', someOtherPlaintextPassword);
})();
/**
* 注册把密码转化为hash存入数据库
*/
async function register(name: string, pass: string) {
const saltRounds = 10;
db[name] = await bcrypt.hash(pass, saltRounds);
}
/**
* 登陆时从数据库取出密码进行验证
*/
async function login(name: string, pass: string): Promise<void> {
console.log(`${pass}: ` + (await bcrypt.compare(pass, db[name])));
}
run
λ npm start
[0] not_bacon: false
[0] hello world: true
相关文章
- Docker NodeJs 服务模板
- Windows下搭建NodeJS绿色版开发环境
- 35·灵魂前端工程师养成-使用nodejs实现简单nginx功能
- ES6转ES5_nodejs支持es6吗
- Nodejs相关ORM框架分析_2023-02-27
- NodeJS 基于 Dapr 构建云原生微服务应用,从 0 到 1 快速上手指南
- pm2:在生产环境中运行 nodejs 应用
- babel : 无法加载文件 D:softwarenodeJsnode-v14.15.4-win-x64babel.ps1,因为在 此系统上禁止运行脚本。有关详细信息,请参阅 https:/g
- 使用代理ip来规避的做法用nodejs具体要怎么做?
- Nodejs开发规范
- 手把手教你做爬虫—基于NodeJs详解编程语言
- Nodejs的运行原理-libuv篇详解编程语言
- NodeJS Stream 三:readable详解编程语言
- Nodejs在Oracle数据库中的应用(node-oracle)
- 将nodejs打包工具整合到鼠标右键的方法
- nodejs中操作mysql数据库示例
- Nodejs+express+html5实现拖拽上传
- NodeJS学习笔记之Connect中间件模块(二)
- Nginx做NodeJS应用负载均衡配置实例