濮阳杆衣贸易有限公司

主頁(yè) > 知識(shí)庫(kù) > 使用mongoose和bcrypt實(shí)現(xiàn)用戶密碼加密的示例

使用mongoose和bcrypt實(shí)現(xiàn)用戶密碼加密的示例

熱門標(biāo)簽:云南外呼系統(tǒng) 廣州長(zhǎng)安公司怎樣申請(qǐng)400電話 電銷機(jī)器人是什么軟件 杭州人工電銷機(jī)器人價(jià)格 濟(jì)南電銷機(jī)器人加盟公司 怎么投訴地圖標(biāo)注 老虎洗衣店地圖標(biāo)注 蘋果汽車租賃店地圖標(biāo)注 呼和浩特電銷外呼系統(tǒng)加盟

前面的話

最近在做的個(gè)人項(xiàng)目中,需要對(duì)密碼進(jìn)行加密保存,對(duì)該操作的詳細(xì)步驟記錄如下

介紹

關(guān)于mongoose已經(jīng)寫過(guò)博客就不再贅述,下面主要介紹bcrypt

bcrypt是一個(gè)由兩個(gè)外國(guó)人根據(jù)Blowfish加密算法所設(shè)計(jì)的密碼散列函數(shù)。實(shí)現(xiàn)中bcrypt會(huì)使用一個(gè)加鹽的流程以防御彩虹表攻擊,同時(shí)bcrypt還是適應(yīng)性函數(shù),它可以借由增加迭代之次數(shù)來(lái)抵御暴力破解法

使用npm安裝即可

npm install --save bcrypt

用戶模型

下面來(lái)創(chuàng)建代碼用戶user的schema,用戶名不能重復(fù)

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前置鉤子,在密碼保存之前,自動(dòng)地把密碼變成hash。詳細(xì)代碼如下

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

在node.bcrypt.js中SALT_WORK_FACTOR默認(rèn)使用的是10,這里設(shè)置為5

驗(yàn)證

加密之后,密碼原文被替換為密文了。我們無(wú)法解密,只能通過(guò)bcrypt的compare方法,對(duì)再次傳入的密碼和數(shù)據(jù)庫(kù)中保存的加密后的密碼進(jìn)行比較,如果匹配,則登錄成功

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

把上面的幾個(gè)步驟串在一起,完整代碼如下

var mongoose = require('mongoose'),
 Schema = mongoose.Schema,
 bcrypt = require('bcrypt'),
 SALT_WORK_FACTOR = 5;
var UserSchema = new Schema({
 username: { type: String, required: true, index: { unique: true } },
 password: { 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, function(err, salt) {
  if (err) return next(err);
  // hash the password using our new salt
  bcrypt.hash(user.password, salt, function(err, hash) {
   if (err) return next(err);
   // override the cleartext password with the hashed one
   user.password = hash;
   next();
  });
 });
});
UserSchema.methods.comparePassword = function(candidatePassword, cb) {
 bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
  if (err) return cb(err);
  cb(null, isMatch);
 });
};
module.exports = mongoose.model('User', UserSchema);

測(cè)試

把上面的代碼保存成user-model.js,然后運(yùn)行下面代碼來(lái)實(shí)際測(cè)試

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' }, function(err, user) {
  if (err) throw err;
  // test a matching password
  user.comparePassword('Password123', function(err, isMatch) {
   if (err) throw err;
   console.log('Password123:', isMatch); // -> Password123: true
  });
  // test a failing password
  user.comparePassword('123Password', function(err, isMatch) {
   if (err) throw err;
   console.log('123Password:', isMatch); // -> 123Password: false
  });
 });
});

控制臺(tái)中輸入如下數(shù)據(jù):

數(shù)據(jù)庫(kù)數(shù)據(jù)如下:

以上這篇使用mongoose和bcrypt實(shí)現(xiàn)用戶密碼加密的示例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

您可能感興趣的文章:
  • Express下采用bcryptjs進(jìn)行密碼加密的方法
  • PHP更安全的密碼加密機(jī)制Bcrypt詳解
  • 密碼哈希函數(shù) Bcrypt的最大密碼長(zhǎng)度限制詳解
  • Java通過(guò)BCrypt加密過(guò)程詳解

標(biāo)簽:無(wú)錫 玉林 遼陽(yáng) 興安盟 廈門 自貢 泰安 雞西

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《使用mongoose和bcrypt實(shí)現(xiàn)用戶密碼加密的示例》,本文關(guān)鍵詞  使用,mongoose,和,bcrypt,實(shí)現(xiàn),;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《使用mongoose和bcrypt實(shí)現(xiàn)用戶密碼加密的示例》相關(guān)的同類信息!
  • 本頁(yè)收集關(guān)于使用mongoose和bcrypt實(shí)現(xiàn)用戶密碼加密的示例的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章
    平山县| 台南县| 安仁县| 城固县| 渭南市| 靖西县| 苍梧县| 阳泉市| 祥云县| 交口县| 石城县| 瑞金市| 遂溪县| 永寿县| 托里县| 陵水| 肃宁县| 嵊泗县| 宜黄县| 龙陵县| 桃园县| 安徽省| SHOW| 屏东县| 苍梧县| 广宁县| 滨海县| 怀安县| 松滋市| 林甸县| 黄龙县| 福海县| 西华县| 友谊县| 百色市| 白山市| 都江堰市| 雷山县| 三穗县| 伊宁市| 报价|