Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
SQL Data Encryption
Next article icon

NPM bcrypt

Last Updated : 10 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

bcrypt is a popular npm package used for password hashing. It utilizes the bcrypt hashing algorithm, which is designed to be slow and computationally intensive, making it resistant to brute-force attacks even with the increasing computational power of modern hardware.

What is bcrypt?

bcrypt is a password-hashing function designed by Niels Provos and David Mazières and presented at USENIX in 1999 to securely hash passwords. It is based on the Blowfish cipher and incorporates a salt to protect against rainbow table attacks and other common password-cracking techniques. Bcrypt is widely used in the industry and is considered one of the most secure methods for hashing passwords.

The bcrypt function accepts a password string (up to 72 bytes), a numeric cost, and a salt value of 16 bytes (128 bits). Usually, the salt is an arbitrary number. These inputs are used by the bcrypt function to calculate a 24-byte (192-bit) hash. The final output of the bcrypt function is a string of the form:

$2<a/b/x/y>$[cost]$[22 character salt][31 character hash]

Example:

$2a$12$R9h/cIPz0gi.URNNX3kh2OPST9/PgBkqquzi.Ss7KIUgO2t0jWMUW
\__/\/ \____________________/\_____________________________/
Alg Cost Salt Hash

Where:

$2a$: The hash algorithm identifier (bcrypt)

12: Input cost (212 i.e. 4096 rounds)

R9h/cIPz0gi.URNNX3kh2O: A base-64 encoding of the input salt

PST9/PgBkqquzi.Ss7KIUgO2t0jWMUW: A base-64 encoding of the first 23 bytes of the computed 24 byte hash

Installation

You can install this package with npm using following command:

npm install bcrypt
or
npm i bcrypt

Basic Usage:

Once installed, you can include bcrypt in your code using the require function:

const bcrypt = require('bcrypt');

Hashing a Password

To hash a password using bcrypt, you'll typically use the " bcrypt.hash() " function.

JavaScript
const bcrypt = require('bcrypt');  const password = 'gfgDemoPassword'; const saltRounds = 10;  bcrypt.hash(password, saltRounds, function (err, hash) {     if (err) {         console.error(err);         return;     }     console.log(hash); }); 

In this example, saltRounds is the number of salt rounds to use. The higher the number of salt rounds, the more computationally intensive the hashing process becomes ( inc. security).

hashing

Comparing a Password

To compare a plain-text password with a hashed password, you can use the bcrypt.compare() function.

JavaScript
const bcrypt = require("bcrypt");  const hashedPassword =     "$2b$10$iGg/9uZhbLVhl.BkFnfNoO0OGnLuweX.URICnzXIePPz5uCFrj7uu"; const plainPassword = "gfg1122";  bcrypt.compare(plainPassword, hashedPassword, function (err, result) {     if (err) {         console.error(err);         return;     }     if (result) {         console.log("Password is correct!");     } else {         console.log("Password is incorrect!");     } }); 

In this example, plainPassword is the plain-text password that you want to compare, and hashedPassword is the hashed password retrieved from your database. The bcrypt.compare() function compares the plain-text password with the hashed password and returns a boolean value indicating whether the passwords matches or not.

Screenshot-2024-05-08-152210
When entered wrong password


correct
When entered correct password

Why do we use bcrypt for password hashing?

The reasons why bcrypt is the preferred choice for password hashing are following:

  • Slow runtime:The slow working of the Bcrypt algorithm makes it difficult for hackers to break password hashes because it takes time to generate hashes and decode them. Security software or a user can detect unusual activity and stop hackers from accessing sensitive data because it takes longer for a threat actor to act.
  • Usage of salt: Rainbow table-resistant password hashes can be produced by adding a random piece of data and hashing it with the password. Password salting ensures the highest security requirements for password storage.
  • Adapts to changes:Bcrypt is a flexible tool that can change to accommodate optimized hardware and software. The hashing password's speed of calculation determines its level of security. As computers get more powerful, hackers can hash passwords more quickly. Bcrypt, on the other hand, employs a variable number of password iterations, which can greatly raise computational costs. Therefore, as computers get faster, bcrypt slows down the hashing process, halting threat actors in the same way that slower, outdated methods would.

Next Article
SQL Data Encryption
author
rohit5swd
Improve
Article Tags :
  • Web Technologies
  • Node.js
  • Node-npm

Similar Reads

  • jwt npm
    JSON Web Token is a way of securely transmitting information between two parties. It is widely used in web applications for authentication and authorization purposes. In this article, we make a project that demonstrates a basic implementation of JWT in a Node.js application. The application features
    3 min read
  • Node.js crypto.scrypt() Method
    The crypto.scrypt() method is an inbuilt application programming interface of the crypto module which is used to enable an implementation of an asynchronous script. Where scrypt is a password-based key derivation function. It is intended to be costly computationally plus memory-wise. So, the brute-f
    3 min read
  • Node.js crypto.pbkdf2() Method
    The crypto.pbkdf2() method gives an asynchronous Password-Based Key Derivation Function 2 i.e. (PBKDF2) implementation. Moreover, a particular HMAC digest algorithm which is defined by digest is implemented to derive a key of the required byte length (keylen) from the stated password, salt, and iter
    2 min read
  • SQL Data Encryption
    In today’s digital era, data security is more critical than ever, especially for organizations storing the personal details of their customers in their database. SQL Data Encryption aims to safeguard unauthorized access to data, ensuring that even if a breach occurs, the information remains unreadab
    5 min read
  • Node.js crypto.hkdfSync( ) Method
    This method provides a synchronous HMAC-based Extract-and-Expand Key Derivation Function key derivation. Key of keylen bytes is derived using digest, given key, salt and info. Syntax: crypto.hkdfSync(digest, key, salt, info, keylen) Parameters: This method has five parameters. digest: It must be str
    2 min read
  • Node crypto.randomBytes() Method
    ​The crypto.randomBytes() method in Node.js is used to generate cryptographically strong pseudo-random data, which is essential for creating secure keys, tokens, and identifiers. This method is part of the built-in crypto module and is available in Node.js versions 10.x and later. Syntax: crypto.ran
    2 min read
  • Encrypting Data in Node.js
    Encryption and Decryption in Node can be done by installing and implementing the 'crypto' library. If you have installed Node.js by manual build, then there is a chance that the crypto library is not shipped with it. You can run the following command to install the crypto dependency. npm install cry
    1 min read
  • Encryption at Rest - MongoDB
    Encryption at rest is a critical security feature that protects stored data from unauthorized access and breaches. MongoDB provides encryption at rest to safeguard data when it is stored on disk, ensuring that even if an attacker gains access to physical storage, the data remains unreadable without
    4 min read
  • Symmetric Key Cryptography
    Symmetrical Key Cryptography also known as conventional or single-key encryption was the primary method of encryption before the introduction of public key cryptography in the 1970s. In symmetric-key algorithms, the same keys are used for data encryption and decryption. This type of cryptography pla
    11 min read
  • Password Hashing with Bcrypt in Flask
    In this article, we will use Password Hashing with Bcrypt in Flask using Python. Password hashing is the process of converting a plaintext password into a hashed or encrypted format that cannot be easily reverse-engineered to reveal the original password. Bcrypt is a popular hashing algorithm used t
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences