One of the best ways to store passwords securely is to salt and hash them.

Salting and hashing converts a plain password to a unique value that is difficult to reverse.

The Bcrypt library lets you hash and salt passwords in Node.js with very little effort.

Phone on top of a thick book, both surrounded by a large metal chain

What Is Password Hashing?

Password hashingmeans passing a plain text password through a hashing algorithm to generate a unique value.

This unique value is called a hash.

Some examples of hashing algorithms are bcrypt, scrypt, and SHA.

This predictability makes hashes vulnerable tobrute-force attacks.

you’re able to mitigate this vulnerability using salting.

What Is Password Salting?

Password saltingadds a random string (the salt) to a password before hashing it.

This way, the hash generated will always be different each time.

Step 3: Generate a Salt

Call thebcrypt.genSalt()method to generate a salt.

It commonly ranges between 5 and 15.

In this tutorial, we will use 10.

Once youve generated the hash, store it in the database.

You will use it to verify a password and authenticate a user trying to enter.

That callback supplies an object containing any errors that occurred, and the overall result from the comparison.

If the password matches the hash, the result is true.

Using Promises

The bcrypt library also supports the use of promises.

For example, here is a function that hashes the password using the then…catch block.

Likewise, this function compares a plain password from the user to a hashed password using promises.

Hashing passwords minimizes the chances of cybercriminals accessing plain passwords and using them to access sensitive data or services.

Salting your hashed passwords makes them even more secure.

Apart from hashing, always validate password strength as an added security measure.