How does bcrypt.compare() verify passwords if it uses different salts?

0
0
Asked By CoolCactus42 On

I'm working on a backend project where I'm using bcrypt to hash user passwords before storing them in the database. As I've learned, bcrypt adds a random salt each time it hashes a password. This means that two users with the same password would have different hashes. My confusion arises when I think about how `bcrypt.compare(password, hash)` can correctly verify a password later on. If the salt is different each time, how does bcrypt recreate the same hash for comparison after the password is stored? I've heard that bcrypt somehow stores the salt along with the hash string itself, but I'm not entirely sure if I've grasped the concept. Can someone explain this to me in simpler terms or give me a step-by-step breakdown?

4 Answers

Answered By DevDolphin99 On

Exactly! In a bcrypt hash, the salt is included in the hashed output. So, when you want to check a password, the bcrypt library will extract the salt from the hash, use it to hash the candidate password, and then compare the two hashes. This is how it ensures security while allowing for password verification.

Answered By CodeWanderer77 On

What you save in the database is basically a combination of the hash and the salt, formatted in such a way that makes both retrievable. It could be something like "hash:salt" or even a fixed length where the first part is the salt and the rest is the hash. When you need to verify a password, you extract the salt and rehash the input password with it.

Answered By TechyTurtle21 On

Yes, the salt is actually a part of the hashed result in bcrypt. It prevents attackers from using precomputed hash tables to crack the hash. When you hash a password, the salt is included in the final result, and it’s crucial for verification. If I remember right, the salt is positioned in the hash string itself, typically between slashes (/).

Answered By CuriousCorgi45 On

To add to that, the bcrypt hashing string includes the salt and other details like version and cost factor. So when you call `bcrypt.compare(password, storedHash)`, it automatically retrieves the necessary salt and hashes the provided password using it. Then it simply checks if the two hashes match.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.