Home Web Front-end JS Tutorial Using bcryptjs password encryption in Express

Using bcryptjs password encryption in Express

Jun 07, 2018 pm 01:38 PM
express Password encryption

This article mainly introduces the method of using bcryptjs for password encryption under Express. Now I share it with you and give it as a reference.

I developed a small project using Express a few days ago. When developing the login and registration module, bcryptjs was used for password encryption. I summarized the content:

bcrypt is a cross-platform file encryption tool. . Files encrypted by it can be transferred on all supported operating systems and processors. Its password must be between 8 and 56 characters and will be converted internally into a 448-bit key.

In addition to encrypting your data, by default, bcrypt will overwrite the original input file three times with random data before deleting it, to thwart attempts to recover it by someone who might gain access to your computer data. If you don't want to use this feature, you can disable it.

bcrypt uses the Blowfish encryption algorithm released by Bruce Schnell in 1993. Specifically, bcrypt is implemented using Paul Kircher's algorithm. The source code distributed with bcrypt is slightly modified from the original version.

Steps to use bcryptjs under Express:

1.Install bcryptjs module

npm install bcryptjs --save
Copy after login

2.Introduce bcryptjs library into the module that needs encryption

var bcrypt = require('bcryptjs');
Copy after login

3. Set the encryption strength

var salt = bcrypt.genSaltSync(10);
Copy after login

4. Generate a HASH value when registering and insert it into the database

router.post('/register', function(req, res, next){
  // 从连接池获取连接
  pool.getConnection(function(err, connection) {
    // 获取前台页面传过来的参数
    var param = req.query || req.params;
    /*生成HASH值*/
    var hash = bcrypt.hashSync(param.pwd,salt);
    // 建立连接 新增用户
    connection.query(userSQL.insert, ["",hash,param.phone,"","","",0], function(err, result) {
      res.send(result);
      // 释放连接
      connection.release();
    });
  });
});
Copy after login

5. Verify the HASH value when logging in and insert it into the database

router.post('/login', function(req, res, next){
  // 从连接池获取连接
  pool.getConnection(function(err, connection) {
    // 获取前台页面传过来的参数
    var param = req.query || req.params;
    // 建立连接 根据手机号查找密码
    connection.query(userSQL.getPwdByPhoneNumber, [param.phone], function(err, result) {
      if(bcrypt.compareSync(param.pwd,result[0].password)){
        res.send("1");
        connection.query(userSQL.updateLoginStatusById, [1,result[0].id], function(err, result) {
        });
      }else{
        res.send("0");
      }
      // 释放连接
      connection.release();
    });
  });
});
Copy after login

The above uses the synchronous usage of bcryptjs. The asynchronous usage is introduced below:

Generate hash password:

bcrypt.genSalt(10, function(err, salt) {
  bcrypt.hash("B4c0/\/", salt, function(err, hash) {
    // Store hash in your password DB.
  });
});
Copy after login

Password verification:

bcrypt.compare("B4c0/\/", hash).then((res) => {
  // res === true
});
Copy after login

The following is the use of Bcrypt to verify the data A simple chestnut of encryption:

var mongoose = require('mongoose');
// 引入bcrypt模块
var bcrypt = require('bcrypt');
// 定义加密密码计算强度
var SALT_WORK_FACTOR = 10;

// 连接数据库
mongoose.connect('mongodb://localhost:27017/test')

// 定义用户模式
var UserSchema = new mongoose.Schema({
  name: {
    unique: true,
    type: String
  },
  password: {
    unique: true,
    type: String
  }
},{ collection: "user"});

// 使用pre中间件在用户信息存储前进行密码加密
UserSchema.pre('save', function(next){
  var user = this;

  // 进行加密(加盐)
  bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt){
    if(err){
      return next(err);
    }
    bcrypt.hash(user.password, salt, function(err, hash){
      if(err){
        return next(err);
      }
      user.password = hash;
      next();
    })
  });
});

// 编译模型
var UserBox = mongoose.model('UserBox', UserSchema);

// 创建文档对象实例
var user = new UserBox ({
  name : "Jack" ,
  password : "123456"
});

// 保存用户信息
user.save(function(err, user){
  if(err){
    console.log(err);
  }else{
    // 如果保存成功,打印用户密码
    console.log("password: " + user.password);
  }
})
Copy after login

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Encapsulated cache class implemented through redis as a cache in nodejs

Use native JavaScript to achieve the magnifying glass effect

Vue Socket.io source code detailed analysis

The above is the detailed content of Using bcryptjs password encryption in Express. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use express to handle file upload in node project How to use express to handle file upload in node project Mar 28, 2023 pm 07:28 PM

How to handle file upload? The following article will introduce to you how to use express to handle file uploads in the node project. I hope it will be helpful to you!

In-depth comparison of Express and Laravel: How to choose the best framework? In-depth comparison of Express and Laravel: How to choose the best framework? Mar 09, 2024 pm 01:33 PM

In-depth comparison of Express and Laravel: How to choose the best framework? When choosing a back-end framework suitable for your project, Express and Laravel are undoubtedly two popular choices among developers. Express is a lightweight framework based on Node.js, while Laravel is a popular framework based on PHP. This article will provide an in-depth comparison of the advantages and disadvantages of these two frameworks and provide specific code examples to help developers choose the framework that best suits their needs. Performance and scalabilityExpr

PHP password encryption and secure storage method? PHP password encryption and secure storage method? Jun 30, 2023 am 08:34 AM

How to handle password encryption and secure storage in PHP? With the rapid development of the Internet, the protection of user privacy and data security has become an important issue. It is crucial for website and app developers to keep user passwords secure. In the PHP language, there are many ways to handle the encryption and secure storage of passwords. This article will introduce some common technologies and best practices to help developers strengthen the security of user passwords. Password Encryption Using Hash Functions When storing passwords, they should never be stored in clear text;

Comparative analysis of Express and Laravel: Choose the framework that suits you better Comparative analysis of Express and Laravel: Choose the framework that suits you better Mar 10, 2024 pm 10:15 PM

Express and Laravel are two very popular web frameworks, representing the excellent frameworks of the two major development languages ​​of JavaScript and PHP respectively. This article will conduct a comparative analysis of these two frameworks to help developers choose a framework that is more suitable for their project needs. 1. Framework Introduction Express is a web application framework based on the Node.js platform. It provides a series of powerful functions and tools that enable developers to quickly build high-performance web applications. Express

PHP and SQLite: How to implement password encryption and verification PHP and SQLite: How to implement password encryption and verification Jul 29, 2023 am 10:17 AM

PHP and SQLite: How to implement password encryption and verification Introduction: In the modern Internet era, the security of user passwords is particularly important. In order to protect users' privacy, websites generally use password encryption and verification methods to store and process users' password information. This article will introduce how to use PHP and SQLite database to implement password encryption and verification functions. 1. Password Encryption Password encryption refers to converting the user's plaintext password into a seemingly unreadable random string. Through this conversion process, even if the database is leaked,

How to use PHP to implement password encryption function How to use PHP to implement password encryption function Aug 19, 2023 am 09:16 AM

How to use PHP to implement password encryption function Password is a security verification method that we often need to use in life and work. In order to protect users' privacy, we must encrypt and store users' passwords to prevent them from being stolen and abused by criminals. This article will introduce how to use PHP to implement password encryption function to increase the security of user passwords. In PHP, there is a very powerful encryption function password_hash() that can be used to generate a hash value of a password. This function can accept two parameters: plain text password and a

In-depth analysis of MySQL password encryption method In-depth analysis of MySQL password encryption method Jun 15, 2023 pm 09:24 PM

With the development of the Internet, MySQL, as an open source relational database management system, is widely used in various applications. One of the important security issues is the encryption and storage of MySQL user passwords. So, what are the methods for MySQL password encryption? This article will give you an in-depth analysis. How MySQL passwords are stored Before understanding the MySQL password encryption method, let’s first understand how MySQL passwords are stored. Before MySQL version 5.7, the one-way hash algorithm (S

How to develop a reliable password encryption and decryption system using PHP and Vue.js How to develop a reliable password encryption and decryption system using PHP and Vue.js Jul 05, 2023 pm 08:53 PM

How to develop a reliable password encryption and decryption system using PHP and Vue.js Introduction: In the online world, password security is particularly important. In order to protect user privacy and security, we need to use a reliable password encryption and decryption system. In this article, we will introduce how to develop a reliable password encryption and decryption system using PHP and Vue.js, with code examples. 1. Understand the principles of password encryption and decryption. Before starting development, we need to understand the principles of password encryption and decryption. In general, we use hashes

See all articles