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!