bcrypt
方式加密我在之前都是使用的md5的方式进行密码加密,因为md5存在必定的风险,并且这个这个依赖已经好久没有更新了,故本次采用的是bcrypt
方式加密。算法
useage(command)npm
npm i bcrypt
const bcrypt = require('bcrypt'); const saltRounds = 10; const myPlaintextPassword = 's0/\/\P4$$w0rD'; const someOtherPlaintextPassword = 'not_bacon';
to hash a passwordpromise
//方式1: bcrypt.genSalt(saltRounds, function(err, salt) { bcrypt.hash(myPlaintextPassword, salt, function(err, hash) { // Store hash in your password DB. }); }); //方式2 bcrypt.hash(myPlaintextPassword, saltRounds, function(err, hash) { // Store hash in your password DB. });
以上两种方式均可以达到相同的加密结果安全
to check password异步
// Load hash from your password DB. bcrypt.compare(myPlaintextPassword, hash, function(err, res) { // 密码正确,会返回的res为true // res == true }); bcrypt.compare(someOtherPlaintextPassword, hash, function(err, res) { // 密码不对,则返回的res 为false // res == false });
值得注意的是:“比较”功能能够对抗定时攻击(使用所谓的“恒定时间”算法)。一般,若是密码,加密密钥或加密哈希与安全性相关,则不要使用常规JavaScript字符串比较函数来比较密码,加密密钥或加密哈希值。函数
promise
方式进行加密bcrypt使用global.Promise中可用的任何Promise实现。 NodeJS> = 0.12内置了一个本机Promise实现。可是,这应该适用于任何Promises / A +兼容的实现。ui
接受回调的异步方法,若是Promise支持可用,则在未指定回调时返回Promise。加密
useagecode
bcrypt.hash(myPlaintextPassword, saltRounds).then(function(hash) { // Store hash in your password DB. });
使用promise
方式验证密码是否一致ip
// Load hash from your password DB. // myPlaintextPassword 为密码, hash为加密后的密码 bcrypt.compare(myPlaintextPassword, hash).then(function(res) { // res == true }); bcrypt.compare(someOtherPlaintextPassword, hash).then(function(res) { // res == false });