服务器之家:专注于服务器技术及软件下载分享
分类导航

Mysql|Sql Server|Oracle|Redis|MongoDB|PostgreSQL|Sqlite|DB2|mariadb|Access|数据库技术|

服务器之家 - 数据库 - MongoDB - 使用mongoose和bcrypt实现用户密码加密的示例

使用mongoose和bcrypt实现用户密码加密的示例

2020-05-17 16:27小火柴的蓝色理想 MongoDB

下面小编就为大家分享一篇使用mongoose和bcrypt实现用户密码加密的示例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

前面的话

最近在做的个人项目中,需要对密码进行加密保存,对该操作的详细步骤记录如下

介绍

关于mongoose已经写过博客就不再赘述,下面主要介绍bcrypt

bcrypt是一个由两个外国人根据Blowfish加密算法所设计的密码散列函数。实现中bcrypt会使用一个加盐的流程以防御彩虹表攻击,同时bcrypt还是适应性函数,它可以借由增加迭代之次数来抵御暴力破解法

使用npm安装即可

?
1
npm install --save bcrypt

用户模型

下面来创建代码用户user的schema,用户名不能重复

?
1
2
3
4
5
6
7
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。详细代码如下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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,这里设置为5

验证

加密之后,密码原文被替换为密文了。我们无法解密,只能通过bcrypt的compare方法,对再次传入的密码和数据库中保存的加密后的密码进行比较,如果匹配,则登录成功

?
1
2
3
4
5
6
UserSchema.methods.comparePassword = function(candidatePassword, cb) {
 bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
  if (err) return cb(err);
  cb(null, isMatch);
 });
};

把上面的几个步骤串在一起,完整代码如下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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,然后运行下面代码来实际测试

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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
  });
 });
});

控制台中输入如下数据:

使用mongoose和bcrypt实现用户密码加密的示例

数据库数据如下:

使用mongoose和bcrypt实现用户密码加密的示例

以上这篇使用mongoose和bcrypt实现用户密码加密的示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://www.cnblogs.com/xiaohuochai/p/8440272.html

延伸 · 阅读

精彩推荐
  • MongoDBMongodb索引的优化

    Mongodb索引的优化

    MongoDB 是一个基于分布式文件存储的数据库。由 C++ 语言编写。接下来通过本文给大家介绍Mongodb索引的优化,本文介绍的非常详细,具有参考借鉴价值,感...

    MRR3252020-05-05
  • MongoDB在mac系统下安装与配置mongoDB数据库

    在mac系统下安装与配置mongoDB数据库

    这篇文章主要介绍了在mac系统下安装与配置mongoDB数据库的操作步骤,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪...

    CXYhh1219312021-11-14
  • MongoDBmongodb数据库基础知识之连表查询

    mongodb数据库基础知识之连表查询

    这篇文章主要给大家介绍了关于mongodb数据库基础知识之连表查询的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用mongodb具有一定的参...

    ZJW02155642020-05-22
  • MongoDBMongoDB多条件模糊查询示例代码

    MongoDB多条件模糊查询示例代码

    这篇文章主要给大家介绍了关于MongoDB多条件模糊查询的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用MongoDB具有一定的参考学习价值...

    浅夏晴空5902020-05-25
  • MongoDBMongoDB的索引

    MongoDB的索引

    数据库中的索引就是用来提高查询操作的性能,但是会影响插入、更新和删除的效率,因为数据库不仅要执行这些操作,还要负责索引的更新 ...

    MongoDB教程网2532020-05-12
  • MongoDBMongoDB系列教程(五):mongo语法和mysql语法对比学习

    MongoDB系列教程(五):mongo语法和mysql语法对比学习

    这篇文章主要介绍了MongoDB系列教程(五):mongo语法和mysql语法对比学习,本文对熟悉Mysql数据库的同学来说帮助很大,用对比的方式可以快速学习到MongoDB的命...

    MongoDB教程网3252020-05-01
  • MongoDBWindows下MongoDB配置用户权限实例

    Windows下MongoDB配置用户权限实例

    这篇文章主要介绍了Windows下MongoDB配置用户权限实例,本文实现需要输入用户名、密码才可以访问MongoDB数据库,需要的朋友可以参考下 ...

    MongoDB教程网3082020-04-29
  • MongoDBMongoDB查询之高级操作详解(多条件查询、正则匹配查询等)

    MongoDB查询之高级操作详解(多条件查询、正则匹配查询等)

    这篇文章主要给大家介绍了关于MongoDB查询之高级操作(多条件查询、正则匹配查询等)的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者...

    w田翔3872020-12-19