It is a developer's job to ensure user data safety. We try to achieve this using different security techniques that help to store the passwords in a secure manner. One of those techniques that is widely adopted is salting and hashing which significantly enhances the security of the passwords.

In this article, we will learn how to use a popular salting and hashing technique known as Bcrypt to make the passwords hard to decipher so that even when the database server is penetrated into, cybercriminals will still have a hard time getting the original password.

As an added security measure, ensure that the users create strong passwords. This article explains how to create strong passwords.
How to Create a strong Wi-Fi password - Hard to guess and easy to remember
In this guide, you get to see how you can create your own encryption algorithm to encrypt your passwords which makes it hard for other people to guess and easy for you to remember.

What is Bcrypt, Salt, and Hash?

Bcrypt is a password hashing algorithm based on the Blowfish cipher that helps to protect against rainbow table attacks. With Bcrypt, developers are able to control the hashing cost which makes it computationally expensive and time-consuming for potential attackers. This algorithm was developed by Niels Provos and David Mazieres.

Password Hashing

Hashing is a cryptographic technique that transforms plain text and passwords into a unique and irreversible form. This ensures that attackers can not reverse the hashed value back into the original password. Hashing plays an important role in keeping passwords secure but they have a vulnerability that can be attacked.

A good hashing algorithm ensures that the hash value generated is always the same when fed with the same input. This means that using the rainbow table an attacker can brute force his way into sensitive data. To avoid this, developers will add salts to make it more difficult to get the password.

Password Salting

Salt is a random string that is added to the original password before hashing. This means that the hash value generated will always be different thus it becomes almost impossible for the attacker to reverse the password. Now that we understand what hashing and salting are, let's see how to use bcrypt to hash passwords before they are stored in the database.

Hashing Passwords Using Bcrypt

Bcrypt is available as an npm package which makes it easy to integrate it into your node js project. Before we begin, ensure that Node is installed on your machine. You can follow our tutorial on how to install Node.

How to install Node JS in ubuntu 20.04
In this guide, you will learn how to install/configure Node JS and npm on ubuntu 20.04 and write your first program.

Project Set up

Start by Creating your project folder in the location of your choice and cd into it. You can do that using the command below.

mkdir bcrypt && cd bcrypt

Inside the folder, initialize a new project using the npm init command

npm init -y

This command will create a new package.json file. Create your entry file and start writing code.

touch app.js

Install and Import Bcrypt into your Project

The next step is to install bcrypt via npm.

npm install --save bcrypt

Once installed, import bcrypt at the top of your JavaScript file as shown below

const bcrypt = require("bcrypt")

Generate a salt on a separate function

Let's initialize some variables.

const saltRounds = 12
const password = "EnterYourPassHere"

Your code should look like this so far.

With the variable set, use the bcrypt.genSalt() function to generate the salt. This function takes in the saltRounds variable that we have set already and a callback function that has the salt and err as the parameters. Here is the function in action.

const bcrypt = require("bcrypt")

const saltRounds = 12
const password = "EnterYourPassHere"

// generate salt
bcrypt.genSalt(saltRounds, (err, salt) => {
    console.log("Salt:", salt)

    // hash password
    bcrypt.hash(password, salt, (err, hash) => {
        console.log("Hashed Password:", hash)
        // Now you can store the password hash in your database.

Once the salt is generated, it goes through the bcrypt.hash() function that takes in three parameters. The password which we have, the salt that has been generated, and a callback function. The resulting output is a hashed password.

Run your program with the command below to see the program in action.

node app.js

In place of app.js, use the name of your project file. If the code runs successfully, you should see something similar in your console.


Generate Salt and Hash in the same Function

Instead of Using two functions to generate the salt and hash the password, You can use one function to do all that. Here is how the functions look like.

const bcrypt = require("bcrypt")

const saltRounds = 12
const password = "EnterYourPassHere"

// hash password using one function
bcrypt.hash(password, saltRounds, (err, hash) => {
  console.log("Hash:", hash);

This function takes in the password, the saltRound, and a callback function that returns an error if the hashing failed and the hash if the encryption was successful.


Comparing Passwords using Bcrypt

Password comparison comes in during authentication. You will need to compare the password that the user provides and the password that is stored in the database. Luckily, bcrypt has a compare function that makes it easy to do the comparison. The compare() function takes in the input password, stored password, and a callback function. Here is how it looks.

const bcrypt = require("bcrypt")

const password = 'user_input_password';
const storedPassword = '...'; // Fetch the stored hashed password from the database, storedPassword, (err, result) => {
  if (result) {
    console.log('Password matched!');
    // Proceed with the login process
  } else {
    console.log('Password does not match!');
    // Reject the login attempt

The callback function should return a Boolean value depending on whether the passwords match.

Wrapping Up!

As seen in this article, the bcrypt library plays a huge role in ensuring user data security. The bcrypt library can hash passwords with different rounds of salts to make it hard to decipher the passwords. As much as the bcrypt library helps to keep the password secure, we can never assume that the database is impenetrable, with a database compromised, one can lose other useful information so. as an added security measure, make sure that your users use strong passwords. Learn how to create a strong password in this article.

If you found the article helpful, consider sharing it with those that would find it interesting and subscribe to Geekbits.

Thanks for reading : )

Table of Contents
Great! Next, complete checkout for full access to GeekBits.
Welcome back! You've successfully signed in.
You've successfully subscribed to GeekBits.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info has been updated.
Your billing was not updated.