0
0
Expressframework~15 mins

Password hashing with bcrypt in Express - Deep Dive

Choose your learning style9 modes available
Overview - Password hashing with bcrypt
What is it?
Password hashing with bcrypt is a way to securely store user passwords by turning them into a scrambled code that is hard to reverse. Instead of saving the actual password, bcrypt creates a unique hash that represents it. When a user logs in, bcrypt compares the entered password by hashing it again and checking if it matches the stored hash. This keeps passwords safe even if someone steals the stored data.
Why it matters
Without password hashing like bcrypt, if a hacker steals a database, they get all user passwords in plain text, risking user accounts everywhere. Bcrypt protects users by making stolen password data useless because hashes cannot be easily turned back into original passwords. This helps prevent identity theft, account takeovers, and builds trust in applications.
Where it fits
Before learning bcrypt, you should understand basic JavaScript, how Express handles requests, and what passwords are. After bcrypt, you can learn about user authentication flows, session management, and advanced security practices like multi-factor authentication.
Mental Model
Core Idea
Bcrypt transforms a password into a unique, irreversible code that can be checked but never reversed to reveal the original password.
Think of it like...
It's like turning a key into a unique lock pattern that only fits that key, but you can't recreate the key from the lock pattern itself.
Password Input
    ↓
[ Bcrypt Hash Function ]
    ↓
Stored Hash (scrambled code)

Login Attempt
    ↓
[ Bcrypt Hash Function ]
    ↓
Compare with Stored Hash → Match? Access granted
Build-Up - 6 Steps
1
FoundationWhat is Password Hashing?
🤔
Concept: Password hashing means changing a password into a fixed-length code that hides the original password.
When you type a password, instead of saving it as is, the system uses a special function to scramble it into a hash. This hash looks like random letters and numbers and cannot be turned back into the original password easily.
Result
Passwords are stored safely as hashes, not plain text.
Understanding that passwords should never be stored as plain text is the first step to securing user data.
2
FoundationWhy Use Bcrypt Specifically?
🤔
Concept: Bcrypt is a hashing method designed to be slow and include a salt to protect against attacks.
Bcrypt adds a random string called a salt to each password before hashing. It also repeats the hashing many times to slow down attackers trying to guess passwords. This makes it much harder to crack passwords even if hashes are stolen.
Result
Each password hash is unique and resistant to common cracking methods.
Knowing that bcrypt’s salt and slowness protect passwords helps you appreciate why simple hashing is not enough.
3
IntermediateHow to Hash Passwords in Express
🤔Before reading on: do you think hashing happens before or after saving the password to the database? Commit to your answer.
Concept: You hash passwords before saving them to the database to keep them secure.
In Express, you use the bcrypt library to hash passwords. When a user signs up, you call bcrypt.hash(password, saltRounds) to create a hash, then save that hash instead of the password. SaltRounds controls how slow the hashing is.
Result
User passwords are stored as bcrypt hashes in the database.
Understanding when and how to hash passwords prevents storing unsafe plain text passwords.
4
IntermediateVerifying Passwords on Login
🤔Before reading on: do you think you compare the plain password or the hash when checking login? Commit to your answer.
Concept: You compare the entered password by hashing it and checking if it matches the stored hash.
When a user logs in, you use bcrypt.compare(enteredPassword, storedHash) which hashes the entered password and checks if it matches the stored hash. This way, you never reveal or use the plain password directly.
Result
Users can log in only if their password matches the stored hash.
Knowing how to verify passwords securely is key to safe authentication.
5
AdvancedChoosing Salt Rounds and Performance
🤔Before reading on: do you think higher salt rounds make hashing faster or slower? Commit to your answer.
Concept: Salt rounds control how many times bcrypt hashes the password, affecting security and speed.
Higher salt rounds mean bcrypt repeats hashing more times, making it slower but more secure. You must balance security with user experience because too slow hashing can delay login or signup.
Result
You pick a salt round value that protects passwords without hurting app speed.
Understanding this tradeoff helps you configure bcrypt for real-world applications.
6
ExpertSecurity Pitfalls and Advanced Usage
🤔Before reading on: do you think reusing the same salt for all passwords is safe? Commit to your answer.
Concept: Each password must have a unique salt; reusing salts or weak configurations weakens security.
Bcrypt automatically generates a unique salt per password. Avoid manually reusing salts or using outdated bcrypt versions. Also, be aware of timing attacks and always use bcrypt’s compare function instead of manual comparisons.
Result
Your password storage resists advanced attacks and follows best security practices.
Knowing these subtle security details prevents common but dangerous mistakes in password hashing.
Under the Hood
Bcrypt works by generating a random salt and combining it with the password. It then applies a key derivation function called Eksblowfish multiple times (controlled by salt rounds) to produce a hash. This process is slow by design to resist brute-force attacks. The salt is stored with the hash so verification can repeat the process exactly.
Why designed this way?
Bcrypt was created to improve on simple hashing by adding salt and adjustable slowness to protect against fast cracking methods like rainbow tables and GPU attacks. Alternatives like MD5 or SHA are fast and unsalted, making them vulnerable. Bcrypt balances security and usability.
┌───────────────┐
│ User Password │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Generate Salt │
└──────┬────────┘
       │
       ▼
┌─────────────────────────────┐
│ Eksblowfish Key Derivation  │
│ (Repeated hashing rounds)   │
└──────┬──────────────────────┘
       │
       ▼
┌───────────────┐
│  Store Hash   │
│ (with Salt)   │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do you think bcrypt hashes can be reversed to get the original password? Commit yes or no.
Common Belief:Many believe bcrypt hashes can be reversed if you have enough computing power.
Tap to reveal reality
Reality:Bcrypt hashes are designed to be one-way and cannot be reversed to reveal the original password.
Why it matters:Believing hashes can be reversed may lead to unsafe password storage or overconfidence in weak security.
Quick: Do you think using the same salt for all passwords is safe? Commit yes or no.
Common Belief:Some think using one salt for all passwords is fine because it adds some randomness.
Tap to reveal reality
Reality:Using the same salt defeats the purpose of salting; each password must have a unique salt to prevent attacks.
Why it matters:Reusing salts makes it easier for attackers to crack multiple passwords at once.
Quick: Do you think bcrypt hashing is fast enough to use without delay concerns? Commit yes or no.
Common Belief:People often believe bcrypt hashing is instant and does not affect user experience.
Tap to reveal reality
Reality:Bcrypt intentionally slows hashing to improve security, which can cause noticeable delays if salt rounds are too high.
Why it matters:Ignoring performance can frustrate users or cause timeouts in applications.
Quick: Do you think comparing hashes with simple equality checks is secure? Commit yes or no.
Common Belief:Some developers compare hashes using '==' or '===' operators directly.
Tap to reveal reality
Reality:Direct comparison can be vulnerable to timing attacks; bcrypt.compare uses safe methods to avoid this.
Why it matters:Using unsafe comparisons can leak information and weaken security.
Expert Zone
1
Bcrypt hashes include the salt and cost factor inside the stored hash string, allowing verification without separate salt storage.
2
The cost factor (salt rounds) can be increased over time as hardware improves, allowing password security to evolve.
3
Bcrypt is resistant to GPU cracking because its algorithm requires sequential memory access, unlike faster hash functions.
When NOT to use
Avoid bcrypt for hashing very large data or files; it is designed specifically for passwords. For other data, use general-purpose cryptographic hashes like SHA-256. Also, consider Argon2 for newer password hashing needs as it offers better memory-hardness.
Production Patterns
In production, bcrypt is used during user signup to hash passwords and during login to verify them. Salt rounds are chosen based on server capacity, often between 10-12. Hashes are stored in databases with user records. Systems also implement rate limiting and account lockouts to complement bcrypt security.
Connections
Cryptographic Salt
Bcrypt builds on the concept of salt by automatically generating and embedding it in hashes.
Understanding salt helps grasp why bcrypt hashes are unique even for identical passwords.
Hash Functions in Cryptography
Bcrypt is a specialized hash function designed for passwords, extending general cryptographic hash principles.
Knowing general hash functions clarifies why bcrypt adds slowness and salt for security.
Biological Immune System
Both bcrypt and the immune system use layers of defense and slow responses to prevent attacks.
Seeing bcrypt’s slowness as a defense mechanism is like how the immune system delays to identify threats carefully.
Common Pitfalls
#1Storing plain text passwords instead of hashes.
Wrong approach:const password = req.body.password; db.saveUser({ username, password });
Correct approach:const hashed = await bcrypt.hash(req.body.password, 10); db.saveUser({ username, password: hashed });
Root cause:Not understanding the need to protect passwords by hashing before storage.
#2Using a fixed salt for all passwords.
Wrong approach:const salt = 'fixedsalt'; const hashed = bcrypt.hashSync(password + salt, 10);
Correct approach:const hashed = await bcrypt.hash(password, 10); // bcrypt generates unique salt internally
Root cause:Misunderstanding how bcrypt handles salting and trying to do it manually.
#3Comparing hashes with '===' instead of bcrypt.compare.
Wrong approach:if (hashedPassword === bcrypt.hashSync(inputPassword, 10)) { /* login */ }
Correct approach:const match = await bcrypt.compare(inputPassword, hashedPassword); if (match) { /* login */ }
Root cause:Not knowing that hashing the input again produces a different hash due to salt, so direct comparison fails.
Key Takeaways
Bcrypt securely stores passwords by turning them into unique, irreversible hashes with built-in salts.
Always hash passwords before saving and verify them using bcrypt’s compare function to maintain security.
Salt rounds control the balance between security and performance; choose wisely based on your app’s needs.
Avoid common mistakes like storing plain passwords, reusing salts, or unsafe hash comparisons to protect users.
Understanding bcrypt’s design helps build safer authentication systems that resist modern attacks.