Hashing passwords in NodeJS with bcrypt library tutorial (2024)

by Nathan Sebhastian

Posted on May 09, 2021

Reading time: 5 minutes

Hashing passwords in NodeJS with bcrypt library tutorial (1)

The bcrypt npm package is a JavaScript implementation of the bcrypt password hashing function that allows you to easily create a hash out of a password string. Unlike encryption which you can decode to get back the original password, hashing is a one-way function that can’t be reversed once done.

When the user submits a password, the password will be hashed and your JavaScript application needs to store the hash in the database. Later when the user wants to authenticate his or her account, you need to compare the password input with the hash stored in your database to see if it matches.

The bcrypt library makes the process easy by providing you with methods to hash and compare passwords.

To start using the library, you need to install it with your package manager:

npm install bcrypt# oryarn add bcrypt

Then include the module to your JavaScript code with require:

const bcrypt = require("bcrypt");

Creating a password hash with bcrypt

To generate a password using the bycrypt module, you need to call on the hash() method which accepts the following three parameters:

  • The password string that you wish to hash
  • The number of rounds to secure the hash. The number commonly ranges from 5 to 15
  • The callback function to execute when the hash process is finished, passing along the error message and the hash result

Here’s an example of bcrypt.hash() processing the password string "generic":

const bcrypt = require("bcrypt");bcrypt.hash("generic", 5, function (err, hash) { console.log(hash); // TODO: Store the hash in your password DB});

Or you can use the synchronous method equivalent called hashSync():

const bcrypt = require("bcrypt");const myPlaintextPassword = "generic";const hash = bcrypt.hashSync(myPlaintextPassword, 5);console.log(hash);

Generating salt for the hash

A hashing function requires you to add salt into the process. A salt is simply a random data that’s used as an additional input to the hashing function to safeguard your password. The random string from the salt makes the hash unpredictable.

In the code examples above, the salt is auto-generated by bcrypt module, but you can actually generate the salt first before hashing the password.

To generate a salt, you can use the genSalt() method from the module:

const bcrypt = require("bcrypt");bcrypt.genSalt(10, function (err, salt) { console.log(salt); // the random salt string});

Once you have the salt, you can pass it to the hash() method as follows:

const bcrypt = require("bcrypt");bcrypt.genSalt(10, function (err, salt) { bcrypt.hash("generic", salt, function (err, hash) { console.log(hash); // Store hash in your password DB. });});

There’s also a synchronous equivalent for the method called genSaltSync():

const salt = bcrypt.genSaltSync(10);const hash = bcrypt.hashSync("generic", salt);

Note that there’s no differences on the resulting hash whether you generate a salt separately or automatically, but the CPU usage may be lowered when you separate the salt generation and the hash process. You should test if your NodeJS server can handle auto-generating the salt and hash first before separating them.

A note on the salt round number

The salt generation for your hash function can range from a few seconds to many days, depending on how many rounds you passed. The bcrypt module will go through 2^rounds to generate the salt to give you a secure hash.

According to the documentation, here’s the amount of time to process the salt generation on a 2GHz core computer:

rounds=8 : ~40 hashes/secrounds=9 : ~20 hashes/secrounds=10: ~10 hashes/secrounds=11: ~5 hashes/secrounds=12: 2-3 hashes/secrounds=13: ~1 sec/hashrounds=14: ~1.5 sec/hashrounds=15: ~3 sec/hashrounds=25: ~1 hour/hashrounds=31: 2-3 days/hash

The number is just an estimation, so you may want to test the highest rounds with the fastest generation time that your server can support.

Verifying a password with bcrypt

Once you saved the hash to the database, you can compare the user’s plain text input with the stored hash using the compare() method.

The compare() method accepts three parameters:

  • The plain string password for comparison
  • The hash string created earlier
  • And the callback function once the comparison process is finished

The method will pass the error err object and the boolean value result, telling you whether the comparison matches or not.

Here’s an example of the compare() method in action:

const bcrypt = require("bcrypt");bcrypt.hash("generic", 5, function (err, hash) { console.log(hash); // The hash returned, continue to compare bcrypt.compare("generic", hash, function (err, result) { console.log("generic:", result); // generic: true }); bcrypt.compare("falsy", hash, function (err, result) { console.log("falsy:", result); // falsy: false });});

The module also provides the synchronous method compareSync for you to use:

const bcrypt = require("bcrypt");const myPlaintextPassword = "generic";const hash = bcrypt.hashSync(myPlaintextPassword, 5);const result = bcrypt.compareSync(myPlaintextPassword, hash);console.log(result); // true

After the comparison is finished, you need to provide the right authentication code according to the returned result.

Using promise or async/await instead of callback function

Finally, bcrypt module also supports the use of promise and async/await code style, so you can use them instead of callbacks to make your code cleaner.

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

const bcrypt = require("bcrypt");bcrypt .hash("generic", 5) .then((hash) => { return bcrypt.compare("generic", hash) .then((result) => { console.log("generic:", result); // generic: true }); }) .catch((err) => { console.log(err); });

And another example using the async/await style:

const bcrypt = require("bcrypt");async function passwordHashTest(password) { const hash = await bcrypt.hash(password, 5); const result = await bcrypt.compare(password, hash); console.log(result); // true}passwordHashTest("generic"); // test the async function

And that’s how the bcrypt module in NodeJS works 😉

Hashing passwords in NodeJS with bcrypt library tutorial (2024)

FAQs

How to use bcrypt to hash passwords in NodeJs? ›

bcrypt. genSalt(saltRounds, (err, salt) => { if (err) { // Handle error return; } // Salt generation successful, proceed to hash the password }); Once the salt is generated, we combine it with the user's password to compute the hash using the bcrypt. hash() function.

Which is the best password hashing algorithm for node JS? ›

Introducing bcrypt

This ensures that even if two users happen to have the same password, their hashed values will be different because of the unique salt added to each one. By using a cryptographically secure hash function, bcrypt significantly slows down the hashing process, making it computationally expensive.

Is bcrypt safe for password hashing? ›

As you can see in the below table, the cost factor of bcrypt makes it extremely secure against brute force attacks thanks to its slow-working hashing algorithm.

Is bcrypt easy to crack? ›

Gauging the true security of bcrypt

While it may take time for a bcrypt hash to be created, it is deliberately intended to take time to crack. Cracking them is arduous for any threat actor and sets it apart from hashing algorithms MD5 and SHA-256.

What is the best hashing algorithm for passwords? ›

While Argon2id should be the best choice for password hashing, scrypt should be used when the former is not available. Like Argon2id, scrypt has three different parameters that can be configured: the minimum CPU/memory cost parameter (N), the blocksize (r) and the degree of parallelism (p).

Is bcrypt better than SHA256? ›

Another important detail is that SHA256 hashes don't include the salt element, which makes them more susceptible to dictionary-based cyberattacks. So while SHA256 is more suitable for applications that require frequent interaction, bcrypt is a better solution for safely storing passwords.

What to use instead of bcrypt? ›

If you want to store passwords, then bcrypt, scrypt, and argon2 are commonly used. They are available in Go's extended library. SHA is a hashing algorithm but by itself is not meant for password storage. Unlike bcrypt, scrypt and argon2, SHA is designed to be fast.

What is the difference between bcrypt and bcryptjs? ›

bcrypt: Implemented in C and other low-level languages, it is typically used in environments where these languages are prevalent, such as Python, Ruby, and PHP. bcrypt. js: A JavaScript implementation, it is specifically designed for use with Node. js.

Is bcrypt deprecated? ›

bcrypt-nodejs is deprecated and throws a warning on install #8903.

What are the disadvantages of bcrypt? ›

Another drawback of bcrypt is that it may not be suitable for some applications that require fast or frequent hashing operations, such as API authentication or session management. Bcrypt may also introduce some overhead or latency in your system, especially if you use a high work factor.

How long can a bcrypt password be hashed? ›

BCrypt hashed passwords and secrets have a 72 character limit.

How long does it take to crack a bcrypt password? ›

Hive's analysis showed that strong passwords (containing numbers, uppercase and lowercase letters, and symbols) and fairly strong passwords (containing uppercase and lowercase letters) are difficult to crack if they are more than eight characters long — it takes months or years to crack such passwords if they are ...

Can I decode bcrypt? ›

Bcrypt is a hash function, not an encryption function. It cannot be decrypted, in the sense that you send the hash result into a function and get the decrypted version.

What is the fastest secure hash algorithm? ›

xxHash is an Extremely fast Hash algorithm, running at RAM speed limits. It successfully completes the SMHasher test suite which evaluates collision, dispersion and randomness qualities of hash functions.

What level of encryption is bcrypt? ›

Bcrypt uses a 128-bit salt and encrypts a 192-bit magic value. It takes advantage of the expensive key setup in eksblowfish.

How to encrypt a password in NodeJs? ›

Approach
  1. The bcryptjs module is imported. A plain text password password is defined. ...
  2. bcrypt. genSalt(10, function (err, Salt) {...}) ...
  3. Inside the salt generation callback, bcrypt. ...
  4. If an error occurs, an error message is logged. ...
  5. bcrypt. ...
  6. If they match, logs indicate successful encryption and matching.
Jun 12, 2024

How to compare hashed passwords using bcrypt? ›

Well you can't compare two hashed values because the hashed output will always be different. Now this will fail of course! So there is no way to bcrypt the same value twice and get the same output. This is because the salt (app_key) is used to generate a unique string that hashes the value.

How to hash data in node js? ›

For example, when we create a hash we first create an instance of Hash using crypto. createHash() and then we update the hash content using the update( ) function but till now we did not get the resulting hash value, So to get the hash value we use the digest function which is offered by the Hash class.

Top Articles
Credit Suisse CDS Reach Crisis Levels as Banks Rush to Buy Protection
What to Capitalize in a Title | Scribendi
Mchoul Funeral Home Of Fishkill Inc. Services
Mountain Dew Bennington Pontoon
Triumph Speed Twin 2025 e Speed Twin RS, nelle concessionarie da gennaio 2025 - News - Moto.it
Byrn Funeral Home Mayfield Kentucky Obituaries
Northern Whooping Crane Festival highlights conservation and collaboration in Fort Smith, N.W.T. | CBC News
San Diego Terminal 2 Parking Promo Code
Computer Repair Tryon North Carolina
Grand Park Baseball Tournaments
Caroline Cps.powerschool.com
Dumb Money
Job Shop Hearthside Schedule
Gwdonate Org
Becu Turbotax Discount Code
Buy PoE 2 Chaos Orbs - Cheap Orbs For Sale | Epiccarry
Cpt 90677 Reimbursem*nt 2023
Aucklanders brace for gales, hail, cold temperatures, possible blackouts; snow falls in Chch
Cambridge Assessor Database
Acts 16 Nkjv
Ups Print Store Near Me
Laveen Modern Dentistry And Orthodontics Laveen Village Az
Ice Dodo Unblocked 76
Ac-15 Gungeon
Like Some Annoyed Drivers Wsj Crossword
Boxer Puppies For Sale In Amish Country Ohio
2011 Hyundai Sonata 2 4 Serpentine Belt Diagram
Bra Size Calculator & Conversion Chart: Measure Bust & Convert Sizes
JVID Rina sauce set1
FAQ's - KidCheck
How rich were the McCallisters in 'Home Alone'? Family's income unveiled
Vadoc Gtlvisitme App
Imagetrend Elite Delaware
Trust/Family Bank Contingency Plan
Aladtec Login Denver Health
Montrose Colorado Sheriff's Department
Labyrinth enchantment | PoE Wiki
M Life Insider
Brandon Spikes Career Earnings
Bekah Birdsall Measurements
Shoecarnival Com Careers
Doublelist Paducah Ky
Denise Monello Obituary
Babykeilani
Dicks Mear Me
Wrentham Outlets Hours Sunday
Santa Ana Immigration Court Webex
Craigslist Com Brooklyn
Southwind Village, Southend Village, Southwood Village, Supervision Of Alcohol Sales In Church And Village Halls
The Significance Of The Haitian Revolution Was That It Weegy
Craigslist Charlestown Indiana
Latest Posts
Article information

Author: Tish Haag

Last Updated:

Views: 6070

Rating: 4.7 / 5 (47 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Tish Haag

Birthday: 1999-11-18

Address: 30256 Tara Expressway, Kutchburgh, VT 92892-0078

Phone: +4215847628708

Job: Internal Consulting Engineer

Hobby: Roller skating, Roller skating, Kayaking, Flying, Graffiti, Ghost hunting, scrapbook

Introduction: My name is Tish Haag, I am a excited, delightful, curious, beautiful, agreeable, enchanting, fancy person who loves writing and wants to share my knowledge and understanding with you.