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
2.Introduce bcryptjs library into the module that needs encryption
var bcrypt = require('bcryptjs');
3. Set the encryption strength
var salt = bcrypt.genSaltSync(10);
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(); }); }); });
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(); }); }); });
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. }); });
Password verification:
bcrypt.compare("B4c0/\/", hash).then((res) => { // res === true });
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); } })
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!

JavaandJavaScriptaredistinctlanguages:Javaisusedforenterpriseandmobileapps,whileJavaScriptisforinteractivewebpages.1)Javaiscompiled,staticallytyped,andrunsonJVM.2)JavaScriptisinterpreted,dynamicallytyped,andrunsinbrowsersorNode.js.3)JavausesOOPwithcl

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 English version
Recommended: Win version, supports code prompts!

Notepad++7.3.1
Easy-to-use and free code editor

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
