Nodejs 使用 bcrypt 庫加密和驗證密碼


install

λ cnpm i bcrypt -S
λ cnpm install --save @types/bcrypt

example

import * as bcrypt from 'bcrypt';
let passHash: string = '';

(async () => {
  const myPlaintextPassword = 'hello world'; // 我的明文密碼
  const someOtherPlaintextPassword = 'not_bacon'; // 錯誤的密碼

  passHash = await register('ajanuw', myPlaintextPassword);
  login('ajanuw', myPlaintextPassword);
  login('ajanuw', someOtherPlaintextPassword);
})();

/**
 * 注冊把密碼轉化為hash存入數據庫
 * @param name
 * @param pass
 */
async function register(name: string, pass: string) {
  const saltRounds = 10;
  return bcrypt.hash(pass, saltRounds);
}

/**
 * 登陸時從數據庫取出密碼進行驗證
 * @param name
 * @param pass
 */
async function login(name: string, pass: string): Promise<void> {
  console.log(`${pass}: ` + (await bcrypt.compare(pass, passHash)));
}

run

λ npm start
[0] not_bacon: false
[0] hello world: true


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM