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".
- bcrypt is a hashing technique based on "Blowfish block cipher cryptomatic algorithm"
- It is an adaptive function designed by Niels Provos and David Mazières in 1999
- 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?
- Decryption of password hashed with bcrypt is next to impossible.
- One time hashing while signing up
- Key factor is the number of rounds for salting
- Adjust the cost of hashing
- Increasing the number of rounds makes the password more resistant to hacks
How to implement it?
- Install the following module in your app.
- npm install --save bcrypt
- const bcrypt = require('bcrypt');
- Encrypt password and store into database.
- bcrypt.hash('myPassword', 10, function(err, hash) {
-
- });
- Retrieve the hashed password from the database and compare with the user entered password.
- bcrypt.compare('somePassword', hash, function(err, res) {
- if (res) {
-
- } else {
-
- }
- });
- Example -
- const bcrypt = require('bcrypt');
- var mypassword = 'pass';
- console.log(bcrypt.hashSync(mypassword, 10));
- var hash1 = bcrypt.hashSync(mypassword, 10)
- if (bcrypt.compareSync(mypassword, hash1)) {
- console.log('Password matched!');
- } else {
- console.log('Password doesn\'t match');
- }
- if (bcrypt.compareSync(bcrypt.hashSync(mypassword, 10), hash1)) {
- console.log('Password matched!');
- } else {
- console.log('Password doesn\'t match');
- }
Pros
- Protect against rainbow table attacks
- Resistant to brute-force search attacks
Cons
- Due to salting, it makes the algorithm slower
- Maximum password length ranges from 50 to 72 bytes
Reference
- https://www.abeautifulsite.net/hashing-passwords-with-nodejs-and-bcrypt
- https://www.npmjs.com/package/bcrypt
- https://en.wikipedia.org/wiki/Bcrypt