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