I wonder how BCrypt can infer the correctness of a entered password, if the generated hash is different for each run?
Example:
Given password: "password123"
Lets say, I hash the given password 10 times and receive:
$2a$10$Uw0LDj343yp1tIpouRwHGeWflT3.QjDp9DeJ2XiwTIHf1T.pjEy0i
$2a$10$uYWUCEnh4gn00w57VSrYjej.UvhzBL8Wf2doTAGSGfhUMtuGr5bha
$2a$10$cJi3XOkRxxicDjEBibNhNOg5MGM.G/.p70KE75.44ayPQo8kCDxUu
$2a$10$qLcN2obMThH544U967JM5OS0vtcfP.Iq1.f0mZdvWfyeIoWHyr422
$2a$10$5/JssXqJyGHeMQlB4pr7zebTRFSt/2iwYJHF5f7.jdlTxbH4c9Sjq
$2a$10$La1UQKu306aNWkhhfhC5XeX7mfcnfbSchBIpLG6O57gur/U/n/fua
$2a$10$xTzEGVfc1D1UHFeMO95ktOJGFT79ybKUKN.z.MidMjP1XfAeElNEi
$2a$10$i9Y.1Ix6PL1bDwoTYtC49.Y0LKpar/S5qC1SkzFB4vnafikOhHSga
$2a$10$FJNTj5xeVbIcMaf9EhodHu9jJLrJL53QHQK9OuemwMh3WuTfxXEqu
$2a$10$OXMToK5CXeNtRHC3w7eqe.Mr7p4fJanbE28E2Y3MHh6f6cq1chyE6
If we assume that I store the first hash in my database and a user tries to log in a few hours later with correct password. The hash, which is generated while the user tries to log in, is totally different to the hash I have stored in my database.
How does BCrypt determine whether the two hashes refer to the same password?
The hash-values in your example contain all the necessary information to do the verification:
$2y$10$nOUIs5kJ7naTuTFkBy1veuK0kSxUFXfuaOKdOKf9xYT0KKIGSJwFa
| | | |
| | | hash-value = K0kSxUFXfuaOKdOKf9xYT0KKIGSJwFa
| | |
| | salt = nOUIs5kJ7naTuTFkBy1veu
| |
| cost-factor = 10 = 2^10 iterations
|
hash-algorithm = 2y = BCrypt
As you can see, this string contains the algorithm, the cost factor and the salt. With these parameters you can calculate a comparable hash value from the login password. In PHP you can use the function password_verify() to verify the password, it will extract the cost factor and the salt automatically.
// Check if the hash of the entered login password, matches the stored hash.
// The salt and the cost factor will be extracted from $existingHashFromDb.
$isPasswordCorrect = password_verify($password, $existingHashFromDb);