I am going through various password hashing techniques and I found a tutorial which left me a bit dubious about some points. In particular, I just would like if you could reconfirm/explain a few things.For example i found the following function. Now if I understand well what this is doing, it's generating a salt which in case with the following values:
$salt = sprintf("$2a$%02d$", $cost) . $salt; // if $cost = 10 and $salt 234, then it should output $2a$1002d$234?
Secondly, the example for authentication uses the following comparison:
if ( crypt($password, $user->hash) === $user->hash )
and it states that "Hashing the password with its hash as the salt returns the same hash" - now I checked the php documentation and naturally it states the same but I am just trying to understand the concept theoretically (I do not like to reuse stuff even if I know how to use if I don't understand the logic behind it).
My question is why crypt($password, $hash) is returning the same $hash value. I just want to understand the logics behind it. Thank you.
PHP's crypt function will pack all attributes into a 60 character string (for BCrypt).
$2y$10$nOUIs5kJ7naTuTFkBy1veuK0kSxUFXfuaOKdOKf9xYT0KKIGSJwFa
| | | |
| | | hash-value = K0kSxUFXfuaOKdOKf9xYT0KKIGSJwFa
| | |
| | salt = nOUIs5kJ7naTuTFkBy1veu (22 characters)
| |
| cost-factor = 10 = 2^10 iterations
|
hash-algorithm = 2y = BCrypt
Now when you pass the stored hash to the function as the second parameter for verification, the cost factor and the salt will be extracted from this string, and will be reused to calculate the new hash. This hash will be comparable, because the same parameters where used.
The PHP functions password_hash() and password_verify() are just wrappers around the crypt function, and will handle the crucial parts like generating a safe salt.
Take the code you read. and throw it away, burn it, kill it. Just don't use it.
PHP has some really strong build in password functions: password_hash and password_verify
These will create the salt for you so you don't have to keep track of them.
The better and correct answer can be found here: Secure hash and salt for PHP passwords