'How does bcrypt "know" whether a given hash is associated with a given password?
Given a password P
and hash H
, the function bcrypt.compare(P, H)
tells you whether or not H
is a bcrypt hash of P
.
Question: How does bcrypt.compare
do the above? It's mysterious to me since P
may be associated with many different hashes, and bcrypt
itself doesn't seem to have any "memory" of the hashes it creates for P
.
(Bonus question: Am I right to assume that the above implies that each bcrypt hash is associated with exactly one password? Or am I wrong -- may a hash be associated with many passwords?)
Solution 1:[1]
Hashing:
string BCryptHashPassword(password)
{
Byte[] salt = GenerateSomeSalt();
return DoTheHash(password, salt);
}
Verifying:
Boolean BCryptVerifyPassword(password, expectedHash)
{
Byte[] salt = ExtractSaltFromExpectedHash(expectedHash);
String actualHash = DoTheHash(password, salt);
return (actualHash == expectedHash);
}
It hashes the password again with the original salt, and compares them. }
Solution 2:[2]
BCrypt does not only save the hash in H
it also saves among other things the salt used to create the hash (here a full explanation).
Match takes the raw password and the expected hash to match a password, so it simply extracts the salt from the expected hash and reapplies it to the raw password.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Ian Boyd |
Solution 2 | chax |