1. 程式人生 > 資料庫 >使用mongoose和bcrypt實現使用者密碼加密的示例

使用mongoose和bcrypt實現使用者密碼加密的示例

前面的話

最近在做的個人專案中,需要對密碼進行加密儲存,對該操作的詳細步驟記錄如下

介紹

關於mongoose已經寫過部落格就不再贅述,下面主要介紹bcrypt

bcrypt是一個由兩個外國人根據Blowfish加密演算法所設計的密碼雜湊函式。實現中bcrypt會使用一個加鹽的流程以防禦彩虹表攻擊,同時bcrypt還是適應性函式,它可以藉由增加迭代之次數來抵禦暴力破解法

使用npm安裝即可

npm install --save bcrypt

使用者模型

下面來建立程式碼使用者user的schema,使用者名稱不能重複

var mongoose = require('mongoose'),Schema = mongoose.Schema,bcrypt = require('bcrypt');var UserSchema = new Schema({
 username: { type: String,required: true,index: { unique: true } },password: { type: String,required: true }
});
module.exports = mongoose.model('User',UserSchema);

加密

下面加入使用者模型的是Mongoose的中介軟體,該中介軟體使用pre前置鉤子,在密碼儲存之前,自動地把密碼變成hash。詳細程式碼如下

let SALT_WORK_FACTOR = 5
UserSchema.pre('save',function(next) {
 var user = this;
 //產生密碼hash當密碼有更改的時候(或者是新密碼)
 if (!user.isModified('password')) return next();
 // 產生一個salt
 bcrypt.genSalt(SALT_WORK_FACTOR,function(err,salt) {
  if (err) return next(err);
  // 結合salt產生新的hash
  bcrypt.hash(user.password,salt,hash) {
   if (err) return next(err);
   // 使用hash覆蓋明文密碼
   user.password = hash;
   next();
  });
 });
});

在node.bcrypt.js中SALT_WORK_FACTOR預設使用的是10,這裡設定為5

驗證

加密之後,密碼原文被替換為密文了。我們無法解密,只能通過bcrypt的compare方法,對再次傳入的密碼和資料庫中儲存的加密後的密碼進行比較,如果匹配,則登入成功

UserSchema.methods.comparePassword = function(candidatePassword,cb) {
 bcrypt.compare(candidatePassword,this.password,isMatch) {
  if (err) return cb(err);
  cb(null,isMatch);
 });
};

把上面的幾個步驟串在一起,完整程式碼如下

var mongoose = require('mongoose'),bcrypt = require('bcrypt'),SALT_WORK_FACTOR = 5;
var UserSchema = new Schema({
 username: { type: String,required: true }
});
UserSchema.pre('save',function(next) {
 var user = this;
 // only hash the password if it has been modified (or is new)
 if (!user.isModified('password')) return next();
 // generate a salt
 bcrypt.genSalt(SALT_WORK_FACTOR,salt) {
  if (err) return next(err);
  // hash the password using our new salt
  bcrypt.hash(user.password,hash) {
   if (err) return next(err);
   // override the cleartext password with the hashed one
   user.password = hash;
   next();
  });
 });
});
UserSchema.methods.comparePassword = function(candidatePassword,isMatch);
 });
};
module.exports = mongoose.model('User',UserSchema);

測試

把上面的程式碼儲存成user-model.js,然後執行下面程式碼來實際測試

var mongoose = require('mongoose'),User = require('./user-model');
var connStr = 'mongodb://localhost:27017/mongoose-bcrypt-test';
mongoose.connect(connStr,function(err) {
 if (err) throw err;
 console.log('Successfully connected to MongoDB');
});
// create a user a new user
var testUser = new User({
 username: 'jmar777',password: 'Password123'
});
// save user to database
testUser.save(function(err) {
 if (err) throw err;
 // fetch user and test password verification
 User.findOne({ username: 'jmar777' },user) {
  if (err) throw err;
  // test a matching password
  user.comparePassword('Password123',isMatch) {
   if (err) throw err;
   console.log('Password123:',isMatch); // -> Password123: true
  });
  // test a failing password
  user.comparePassword('123Password',isMatch) {
   if (err) throw err;
   console.log('123Password:',isMatch); // -> 123Password: false
  });
 });
});

控制檯中輸入如下資料:

資料庫資料如下:

以上這篇使用mongoose和bcrypt實現使用者密碼加密的示例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。