最近在作的我的项目中,须要对密码进行加密保存,对该操做的详细步骤记录以下html
关于mongoose已经写过博客就再也不赘述,下面主要介绍bcryptnode
bcrypt是一个由两个外国人根据Blowfish加密算法所设计的密码散列函数。实现中bcrypt会使用一个加盐的流程以防护彩虹表攻击,同时bcrypt仍是适应性函数,它能够借由增长迭代之次数来抵御暴力破解法算法
使用npm安装便可mongodb
npm install --save bcrypt
注意:bcrypt之前是能够直接安装的,可是最近发现没法正常安装,可使用cnpm安装bcryptjs来替代数据库
cnpm install --save bcryptjs
const bcrypt = require('bcryptjs')
下面来建立代码用户user的schema,用户名不能重复npm
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。详细代码以下mongoose
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, function(err, hash) { if (err) return next(err); // 使用hash覆盖明文密码 user.password = hash; next(); }); }); });
在node.bcrypt.js中SALT_WORK_FACTOR默认使用的是10,这里设置为5ide
加密以后,密码原文被替换为密文了。咱们没法解密,只能经过bcrypt的compare方法,对再次传入的密码和数据库中保存的加密后的密码进行比较,若是匹配,则登陆成功函数
UserSchema.methods.comparePassword = function(candidatePassword, cb) { bcrypt.compare(candidatePassword, this.password, function(err, isMatch) { if (err) return cb(err); cb(null, isMatch); }); };
把上面的几个步骤串在一块儿,完整代码以下测试
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);
把上面的代码保存成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' }, 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 }); }); });
控制台中输入以下数据:
数据库数据以下: