Nodejs 使用 bcrypt 库加密和验证密码

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
posted @ 2019-08-11 11:52  Ajanuw  阅读(2027)  评论(0编辑  收藏  举报