Jun 10, 2024
4 min read
🔐 Understanding Bcrypt for Password Security 🔐

I've been diving deep into how password hashing works with bcrypt, and here are a few insights that I found interesting:
- Why Can't Hashed Passwords Be Decoded?
When bcrypt hashes a password, it doesn't "decode" it back to the original. Instead, it hashes the entered password again (using the same salt and cost factor) and checks if it matches the stored hash. This is known as hash and compare. - What Does the Second Argument in
bcrypt.hash
Represent?
The second argument inbcrypt.hash("password", rounds)
represents the number of salt rounds (or cost factor), not the salt itself. More rounds = stronger security, but also more computational time! - Where is the Salt in a Bcrypt Hash?
The salt is embedded directly in the resulting hash! A bcrypt hash looks like this:
$2b$10$E9NuY2Uhcj4MR5t2KsFN0eHqCCMeRc7w3Fic8e6.w38JlnFrZftpy
- Prefix (
$2b$
): Indicates the version of the bcrypt algorithm being used. Common prefixes are$2a$
,$2b$
, and$2y$
. - Cost Factor (
10$
): This represents the number of salt rounds (e.g., 10 here) that were used to generate the hash. More rounds make the hash more secure but slower to compute. - Salt (
E9NuY2Uhcj4MR5t2KsFN0e
): The next 22 characters after the cost factor represent the salt. This is a base64-encoded value that was randomly generated during the hashing process. - Hash (
HqCCMeRc7w3Fic8e6.w38JlnFrZftpy
): The remaining part of the string is the actual hash of the password combined with the salt.
- Prefix (
- How Does
bcrypt.compare
Work?
bcrypt.compare
extracts the salt and cost factor from the stored hash and re-hashes the entered password to see if it matches the stored one.
Takeaway: Bcrypt's design makes each password hash unique and self-contained, adding an extra layer of security to stored passwords!