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

相关文章:

  • 2022-12-23
  • 2018-02-11
  • 2021-11-03
  • 2021-06-04
  • 2021-04-01
  • 2021-05-16
  • 2021-11-06
  • 2022-12-23
猜你喜欢
  • 2021-08-25
  • 2022-12-23
  • 2022-12-23
  • 2022-02-25
  • 2021-08-23
  • 2021-12-15
相关资源
相似解决方案