Hashing Passwords with Node.js and Bcrypt

Hashing Passwords with Node.js and Bcrypt

Creating and Verifying a Password Hash Bcrypt supports both sync and async methods. The asynchronous approach is recommended because hashing is CPU intensive, and the synchronous version will block the event loop and prevent your app from handling other requests until it finishes.

Introduction

In this article, we will be using the bcryptjs javascript library for hashing and comparing passwords. Here, we will build a simple API for registering and login. We will hash the password when the user registers, and then compare that password with the hash when they login.

What is bcrypt ?

bcrypt is a password hashing function designed by Niels Provos and David Mazières, based on the Blowfish cipher, and presented at USENIX in 1999. Besides incorporating a salt to protect against rainbow table attacks, bcrypt is an adaptive function. Over time, the iteration count can be increased to make it slower, so it remains resistant to brute-force search attacks even with increasing computation power.

What is hashing?

Hashing is a one-way function (well, a mapping). It's irreversible, you apply the secure hash algorithm and you cannot get the original string back. The most you can do is to generate what's called "a collision", that is, finding a different string that provides the same hash. Cryptographically secure hash algorithms are designed to prevent the occurrence of collisions. You can attack a secure hash by the use of a rainbow table, which you can counteract by applying a salt to the hash before storing it.

Setup Project Folder
  • Open the console type below command to make a new directory
    # mkdir bcrypt

  • Change to the new directory
    # cd bcrypt

Setup Node In Project
  • Now set up our workspace by using the below command:

    npm init
  • This will generate the package.json file which states that the node is correctly setup.

  • This will hold all the metadata related to our project.

Install Packages
  • Now install packages that will be required in our project.
  • Type npm install followed by package name npm install --save bcryptjs express body-parser mongoose
  • After installing packages, package.json will look like this

About packages
  1. Express - it is a framework on which our application will be built.
  2. Body-parser - extract the entire body portion of an incoming request stream and exposes it on req.body.
  3. Mongoose - Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js.It manages relationships between data, provides schema validation, and is used to translate between objects in code and the representation of those objects in MongoDB.
  4. Bcryptjs - this is a Javascript library by which we can hash and compare passwords.
Create Model
  • Create a new folder models and add the file user.js

The user.js will contain the collection schema of our user.

var mongoose = require('mongoose');  
  
var userSchema = new mongoose.Schema({  
    email:{  
        type:String,  
        unique:true  
    },  
    name:{  
        type:String  
    },  
    password:{  
        type:String  
    }  
});  
  
module.exports = mongoose.model('user',userSchema);  
  • mongoose.schema() - Everything in Mongoose starts with a Schema. Each schema maps to a MongoDB collection and defines the shape of the documents within that collection.
  • mongoose.model() - Mongoose model provides an interface to the database for creating, querying, updating, deleting records, etc.

Now we setup our application start point

  • Create a new file name it app.js

App.js

var express     = require('express');  
var bodyParser  = require('body-parser');  
var mongoose    = require('mongoose');  
var userModel   = require('./models/users');  
var bcrypt      = require('bcryptjs');  
  
mongoose.connect('mongodb://localhost:27017/bcrypt',{useNewUrlParser:true})  
.then(function(){  
    console.log('connected to database');  
}).catch(function(error){  
    console.log('error occured'+error);  
});  
  
var app = express();  
  
app.use(bodyParser.urlencoded({extended:false}));  
app.use(bodyParser.json());  
  
app.post('/register',function(req,res){  
    try {  
        var x;  
        console.log(req.body);  
         bcrypt.genSalt(10,function(err,salt){  
         bcrypt.hash(req.body.password,salt,function(err,hash){  
         var userr = new userModel({  
            email:req.body.email,  
            name:req.body.name,  
            password:hash  
        });  
        userr.save(function(err,data){  
          if(err){  
              console.log(err);  
              res.json({er:err});  
          }  
          else{  
              res.json({da:data});  
          }  
        });  
     });  
    });  
    } catch(error){  
        console.log(error);  
         res.json({er:error});  
    }  
});  
app.post('/login',function(req,res){  
    try {  
         userModel.find({email:req.body.email},function(err,data){  
             console.log(data);  
              if(err){  
                  res.json({er:error});  
              }else{  
                  if(data){  
                      console.log('data'+data[0].password);  
                      bcrypt.compare(req.body.password,data[0].password,function(err,result){  
                          if(err){  
  
                              res.json({msg:'email password doesnt matched.Try again!',er:err});  
                          }  
                          else{  
                        res.json({da:result,msg:'password matched'});  
                          }  
                      });  
                  }  
                  else{  
                      res.json({msg:'user doesnt exists'});  
                  }  
              }  
         });  
    } catch (error) {  
        res.json({er:error});  
    }  
});  
  
var port = process.env.PORT || 3000;  
app.listen(port,function(){  
    console.log('server running at port '+port);  
});  
  • genSalt() - This will generate salt .Here we provide number of rounds to use, defaults to 10 if omitted.
  • hash() - this will hash our paswword with the salt.
  • compare() - compares the given data against the given hash.

Click to watch the tutorial

Output
  • register user

  • user login

Thank you for reading!

Hire Node JS Developer from Expert Node JS Development Company

Hire Node JS Developer from Expert Node JS Development Company

NodeJS Development Company-Hire Node JS developer from the most prominent NodeJS development company, Mobiweb and get remarkable Node.js app development services.

Are you looking to hire the most talented and expert Node JS developers for your valuable web application projects and mobile app development projects or you want to migrate application on Node JS framework? Then you have to hire Node JS developer from leading offshore Node JS development company Mobiweb Technologies. We have a team of developers with extensive experience in developing Node JS based applications whether it is web based or mobile app based.

Hire React Js Developer from Expert React JS Development Company

Hire React Js Developer from Expert React JS Development Company

Are you looking to [hire React JS developer](https://www.mobiwebtech.com/react-js-development-company/ "hire React JS developer") from a prestigious and reliable React JS development company? Visit at Mobiweb Technologies here we have a big team...

Are you looking to hire React JS developer from a prestigious and reliable React JS development company? Visit at Mobiweb Technologies here we have a big team of expert React JS developers, you can hire them on an hourly, weekly or monthly basis for the successful completion of your dream project.

Main Reasons of Using Node JS for Your Web Application Development

Main Reasons of Using Node JS for Your Web Application Development

You have to hire Node JS developer from prestigious and expert Node JS development company Mobiweb Technologies. They are tech enthusiasts with new and latest programming ideas, web development technologies and industry trends.

Node JS is the best JavaScript for utilizing in real-time applications. If you are stressed of using low level web sockets or protocols then with the incredible speed of Node JS you can easily develop real-time applications. According to the business perspective, Node JS is highly advantageous for any online business or business website, so it is very difficult for companies or business owners to avoid Node JS for their web application projects. For the best results in your Node JS development project you must have to hire Node JS developer from the prestigious web development company- Mobiweb Technologies.