bcrypt In NodeJS

bcrypt Problem

How we can implement a solution to secure the user's login credentials in Node.js?

Solution

The solution to this problem is "bcrypt".

  1. bcrypt is a hashing technique based on "Blowfish block cipher cryptomatic algorithm"
  2. It is an adaptive function designed by Niels Provos and David Mazières in 1999
  3. It has implementation in C, C++, C#, Go, Java, JavaScript, Elixir, Perl, PHP, Python, Ruby and other languages.

Why one should choose bcrypt over other hashing algorithms?

  1. Decryption of password hashed with bcrypt is next to impossible.
  2. One time hashing while signing up
  3. Key factor is the number of rounds for salting
  4. Adjust the cost of hashing
  5. Increasing the number of rounds makes the password more resistant to hacks

How to implement it?

  1. Install the following module in your app.
    1. npm install --save bcrypt  
    2. const bcrypt = require('bcrypt');  
  1. Encrypt password and store into database.
    1. bcrypt.hash('myPassword', 10, function(err, hash) {  
    2.    // Store hash in database  
    3. });  
  1. Retrieve the hashed password from the database and compare with the user entered password.
    1. bcrypt.compare('somePassword', hash, function(err, res) {  
    2.     if (res) {  
    3.         // Passwords match  
    4.     } else {  
    5.         // Passwords don't match  
    6.     }  
    7. });  
  1. Example -
    1. const bcrypt = require('bcrypt');  
    2. var mypassword = 'pass';  
    3. console.log(bcrypt.hashSync(mypassword, 10));  
    4. var hash1 = bcrypt.hashSync(mypassword, 10)  
    5. if (bcrypt.compareSync(mypassword, hash1)) {  
    6.     console.log('Password matched!');  
    7. else {  
    8.     console.log('Password doesn\'t match');  
    9. }  
    10. if (bcrypt.compareSync(bcrypt.hashSync(mypassword, 10), hash1)) {  
    11.     console.log('Password matched!');  
    12. else {  
    13.     console.log('Password doesn\'t match');  
    14. }  

Pros

  1. Protect against rainbow table attacks
  2. Resistant to brute-force search attacks

Cons

  1. Due to salting, it makes the algorithm slower
  2. Maximum password length ranges from 50 to 72 bytes

Reference

  1. https://www.abeautifulsite.net/hashing-passwords-with-nodejs-and-bcrypt
  2. https://www.npmjs.com/package/bcrypt
  3. https://en.wikipedia.org/wiki/Bcrypt
Next Recommended Reading NodeJS: Convert XML to JSON