Just Learn Code

Secure User Authentication with Bcrypt npm Package

Introduction to bcrypt npm Package

In the era of the internet, web applications are widespread and secure authentication mechanisms are essential. One of the most crucial ways to secure user authentication is through password encryption.

Password encryption is the process of converting plain text passwords into a non-readable format that cannot be easily guessed or decrypted. To achieve this, hashing algorithms are used to create hash values for passwords.

One such algorithm is bcrypt, which is a password hashing function. This article provides an overview of bcrypt npm package, its installation process, and how it is used in password hashing for user authentication.

Comparison Between Encryption and Hashing

It is essential to note that encryption and hashing are not interchangeable terms. In the encryption process, data is converted to an unreadable format (ciphertext) that can only be decrypted using a key.

The key is a password that is passed through an algorithm designed to transform plaintext into ciphertext. On the other hand, hashing algorithms are primarily unique one-way functions that take input, of any length, and give an output of fixed length irrespective of whether the input is changed slightly.

Encryption provides confidentiality and integrity because ciphertext is unreadable without the key. Hashing provides integrity because once the hash is created, it cannot be changed without affecting the original hash value.

Additionally, since encryption requires a key, it is considered more secure than hashing. The plaintext may be vulnerable if the key is compromised.

Storing Password Hashes in a Database for User Authentication

Database storage of user credentials is necessary for efficient logging and authentication. Storing plain passwords is never recommended as it exposes users to potential attacks and data breaches.

For example, if an attacker gains unauthorized access to your database, they can easily obtain all your users’ clear text passwords. To avoid this, we store hashed passwords in the database rather than plaintext passwords.

If attackers gain access to our database, all they’ll see is a string of characters that are virtually useless without a hashing algorithm.

Use of Bcrypt Library for Password Hashing and Comparison

Bcrypt is the most recommended password-hashing library that developers prefer because of its strength and integrity. It became an extremely popular password-hashing algorithm for securing sensitive information in web applications.

Bcrypt npm package has gained increased momentum because it is easy to use. Additionally, the algorithm has a two-step process to produce a hash.

The function takes a password and a salt as input parameters. The salt is included in the algorithm to prevent hacking or duplication.

Installing and Including bcrypt module

To start using bcrypt, you first need to install the package. Install with npm is the most straightforward way to get started.

To install the bcrypt package, type npm install bcrypt in your terminal. After installation, include the module in your JavaScript code with the require() method at the top of your file; require(bcrypt).


Bcrypt npm package introduces an excellent way to store passwords in web applications securely. It is understandable, easy to use, and has a fast performance rate.

As developers continue to work on web applications that require password authentication, using packages like bcrypt npm will ensure their users’ data is safe and secure.

Creating a Password Hash with Bcrypt

Password hashing algorithms are significant in securing data, and Bcrypt is one of the most popular algorithms used today. To create a password hash with Bcrypt, we use the hash() method.

The hash() method takes two parameters: the password we want to hash and a salt. It is important to note that adding salt to the hashing process is crucial to increase the process’s security level.

Using hash() Method to Generate Password Hash

The hash() method is used to generate a password hash. It accepts two parameters: the password we want to hash and the salt value.

The algorithm processes the input and generates an encrypted output. Normally, during the hashing process, the password string is mixed with the salt using a mathematical operation and input to the hash function.

When the hash is completed, you receive a resulting hash string that represents the original password.

Parameters Required for hash() Method

The hash() method requires two parameters. The first parameter is a password string that you want to hash.

The second parameter is the desired salt value. The salt value can be generated using the generate salt() method in Bcrypt.

You can pass a generated salt value to the hash() method to ensure that your password’s hash is more secure.

Example of hash() Method Processing a Password String

Here’s an example of how to use the hash() method to generate a password hash:


const bcrypt = require(‘bcrypt’);

const saltRounds = 10;

const myPlainTextPassword = ‘mypassword’;

bcrypt.genSalt(saltRounds, (err, salt) => {

bcrypt.hash(myPlainTextPassword, salt, (err, hash) => {

console.log(hash); // “$2b$10$8.3pQGaYYxVFUhK5O6FnIOh4vNyPgrFz7zKAbPObKB3rNbNl1WtSe”




Alternative Use of hashSync() for Synchronous Methods

When you need more control over your input stream, there’s also a synchronous version of the hash() method called hashSync(). This method accepts the same parameters as the asynchronous hash() method.

However, it returns the result immediately upon completion, thereby avoiding the need for a callback function.

Generating Salt for the Hash

Another essential aspect of password hashing is using a salt. A salt is a random value that is added to the input stream alongside the password string.

This value makes it more complicated to crack the hash by employing a technique called brute-forcing. While salt doesn’t enhance the security of an individual hash, it improves the collective security of the password system.

Importance of Adding Salt in the Hashing Process

Adding salt to the hashing process reduces the risk of hash attacks known as dictionary attacks and rainbow table attacks. A dictionary attack involves an attacker using a predetermined set of passwords to test against the hash, hoping to find a match.

A rainbow table attack involves an attacker using a pre-constructed table that maps potential passwords to their corresponding hash values.

Use of genSalt() Method to Generate Salt

Bcrypt provides a method called genSalt() to generate salt. The genSalt() method takes one parameter, which defines the number of rounds used to create the salt.

The number of rounds is between 10 and 12, and they can vary based on your security requirements. The amount of time required to generate the salt curve is proportional to the number of rounds.

Passing Salt to hash() Method

Once you’ve generated the salt, you need to pass it to the hash() method, just like an input value. This to ensure that the salt is incorporated into the hashing algorithm.

Alternative Use of genSaltSync() for Synchronous Methods

The synchronous version of the genSalt() method is called genSaltSync(). It takes the same parameter as the asynchronous method and immediately returns a value upon completion without relying on a callback function.


In conclusion, creating a password hash with Bcrypt involves using the hash() method, which takes a password string and a salt. The genSalt() and genSaltSync() methods generate salt values.

Once we have the salt, we pass it to the hash() method. Adding salt to the hashing process is crucial to increase the password hashing process’s security level, and this protects a user’s passwords from being compromised.

A Note on the Salt Round Number

The strength of the bcrypt algorithm is dependent upon the salt round number used. A salt round is the number of iterations the system runs the salt algorithm to generate the salt.

The higher the number of rounds, the more time-intensive the process and the higher the cost and lower the chance for password cracking.

Importance of Salt Generation Rounds for Secure Hash

The salt round number represents the number of times the salt method iterates during the password hashing process. A higher round number represents a higher level of security but also increases the time it takes to generate a hash.

It is crucial to note that depending on the number of salt generation rounds, the computational process of generating secure hashes changes. A high number of rounds create a complex hash that will take more time to break, while a low round number will generate a simpler hash.

Amount of Time for Salt Generation Process on 2GHz Core Computer

The amount of time it takes to generate a hash is proportional to the number of rounds the salt method uses. This can be computationally expensive for larger round numbers.

For instance, generating an 8-round salt on a 2GHz Core computer could take approximately 40 milliseconds. This may not seem like a long time, but the time required increases exponentially as the salt rounds increase.

Testing Highest Rounds with Fastest Generation Time on Server

To determine the optimal salt rounds for your password hashing needs, it is recommended to start with high salt rounds, and work backward until the desired balance between security and computation time is achieved. It’s also advisable to test the highest number of rounds that you can afford on your server with an acceptable generation time.

Verifying a Password with Bcrypt

After creating a hash with bcrypt, we must verify whether passwords entered by a user match the stored hash. Bcrypt provides the compare() method to compare the plaintext password with the stored hash password.

Comparing Plain Text Input with Stored Hash Using compare() Method

The compare() method is used to compare the plaintext password with the stored hashed password. This method accepts three parameters, plaintext password, stored hash password, and a callback function.

If the input and hash match, the callback function will return true, but if there’s no match, it will return false.

Parameters Required for compare() Method

To use the compare() method, we need to pass three parameters to the method. The first two parameters are the plaintext password and the stored hash password, which are compared.

The third parameter is a callback function.

Example of compare() Method in Action

Here’s an example of how to use the compare() method in bcrypt:


const bcrypt = require(‘bcrypt’);

const plainTextPassword = ‘mypassword’;

const hashPassword = ‘$2b$10$8.3pQGaYYxVFUhK5O6FnIOh4vNyPgrFz7zKAbPObKB3rNbNl1WtSe’;

bcrypt.compare(plainTextPassword, hashPassword, function(err, result) {

if (result) {

console.log(‘Password match!’);

} else {

console.log(‘Password does not match!’);




Alternative Use of compareSync() for Synchronous Method

Like the hash() method, Bcrypt has a synchronous version of the compare() method called compareSync(). This method accepts the same parameters as its asynchronous counterpart, but returns the result immediately after completion, without the need for a callback function.

Authentication Code for Returned Result

To authenticate users after a successful password match using the compare() method, most developers use a signed JSON web token (JWT). The authentication code contains the user ID along with a secret key that can only be decrypted by the server, thus enabling secure access to protected pages.


In conclusion, verifying a password using bcrypt is straightforward with the compare() method. Bcrypt compares plaintext passwords with stored hash passwords, and if a match is found using the compare() method, an authentication code is generated.

Using synchronous processing for more streamlined performance and deciding on an appropriate salt round number for your application can enhance security with password hashing through bcrypt. Using Promise or Async/Await Instead of Callback Function

While callback functions are a traditional way to handle asynchronous code, they can be challenging to read and write, particularly for complicated code snippets.

Recognizing this, many modern programming languages introduce more elegant solutions like promises and async/await.

Support for Promise and Async/Await Code Style

Bcrypt npm package fully supports promise and async/await code style.

It has a set of methods that return promises instead of invoking callbacks. This makes code more readable and drastically reduces callback nesting, making it easier to manage complex code structure.

Example of Using Promises in the Hash Process

Promises provide a better way to handle the result of a bcrypt method than callback functions. When the generation process is complete, the methods return a promise in the resolve state if successful and a promise in the reject state if there is an error.

Here’s an example of using promises in the hash process:


const bcrypt = require(‘bcrypt’);

const saltRounds = 10;

const myPlainTextPassword = ‘mypassword’;


.then(salt => {

bcrypt.hash(myPlainTextPassword, salt)

.then(hash => {




.catch(err => console.error(err));


The above code snippet generates a salt value with 10 rounds using the genSalt() method and then hashes the password using the generated salt with hash() method. The results of the hash process are logged to the console.

Example of Using Async/Await Style

Async/await style is another modern solution to callback hell – a series of nested callback functions that can make code complex and confusing. Async/await style ensures code readability, and as the name implies, it provides a more synchronous flow in an async operation.

Here’s an example of using async/await style:


const bcrypt = require(‘bcrypt’);

const saltRounds = 10;

const myPlainTextPassword = ‘mypassword’;

async function hashPassword(){


const salt = await bcrypt.genSalt(saltRounds);

const hash = await bcrypt.hash(myPlainTextPassword, salt);


} catch(error){






In the above code snippet, hashPassword() is an async function that generates a salt value with 10 rounds using the genSalt() method, then hashes the password using the generated salt with hash() method. Promises are implicitly returned in this manner, with the try/catch block handling any errors that may arise in the process.


Bcrypt npm package supports both promise and async/await code style. These modern solutions to callback functions reduce the cognitive load of writing complex code and make it easier for developers to manage projects.

By creating more readable and manageable code, developers can focus on other critical aspects of a web application, thus improving code quality. In conclusion, the bcrypt npm package provides a reliable and efficient method to secure password hashes for web application authentication.

It is essential to understand the differences between hashing and encryption and how to store password hashes in a database. To create a password hash with bcrypt, developers can use the hash() method and generate a salt using the genSalt() method to add an extra layer of security.

Verifying a password with bcrypt only requires a simple compare() method that can be used with promises or async/await code style instead of callback functions. Overall, the use of bcrypt npm package is crucial in modern web development, and it is essential for developers to understand its implementation and features to create secure and scalable web applications.

Popular Posts