1

I got this code off the PHP website. I can make this work without the Salt. But how do you verify with the salt - or does it have to be stored into a variable then you use that later? Not sure how to proceed to the next step to verify. Lots of tutorials on how to make a hash, but to verify is another thing. Thank you.

$options = [
'cost' => 11,
'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM),
];
echo password_hash("rasmuslerdorf", PASSWORD_BCRYPT, $options)."\n";


// See the password_hash() example to see where this came from.
$hash = '$2y$11$nJp/w0OC41I0m44T9OQKBuWUrQi63PrJuvDc68KI6oDBdnZK01kiW ';

if (password_verify('rasmuslerdorf', $hash)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
DDJ
  • 807
  • 5
  • 13
  • 31

1 Answers1

4

Note that password_hash() returns the algorithm, cost and salt as part of the returned hash. Therefore, all information that's needed to verify the hash is included in it. This allows the verify function to verify the hash without needing separate storage for the salt or algorithm information.

Source: http://php.net/manual/en/function.password-verify.php

just use the function as you did above, it will automatically detect the salt.

If omitted, a random salt will be generated by password_hash() for each password hashed. This is the intended mode of operation.

source:http://php.net/manual/en/function.password-hash.php

Even if you don't add a salt, password_hash will automatically add a random generated one, so you shouldn't have any problem verifying a password that has been salted.

Also note that:

The salt option has been deprecated as of PHP 7.0.0. It is now preferred to simply use the salt that is generated by default.

  • 1
    I guess what is confusing me is: Wasn't Salt added to help make it harder to encrypt and now if it is included randomly how would PHP know how to unencrypt it unless it had the salt in a separate variable or database? – DDJ Mar 26 '16 at 18:10
  • 1
    For example let's say that password_hash() function generated this hash :`$2a$10$vI8aWBnW3fID.ZQ4/zo1G.q1lRps.9cGLcZEiGDMVr5yUP1KUOYTa`. `2a` identify the crypting algorithm (in this case BCRYPT), `10` is the cost ( in your case will be 11) and `vI8aWBnW3fID.ZQ4/zo1G.q1lRps.9cGLcZEiGDMVr5yUP1KUOYTa` is the salt and the cipher text, concatenated and encoded in a modified Base-64. The first 22 characters decode to a 16-byte value for the salt. Check this [answer](http://stackoverflow.com/questions/6832445/how-can-bcrypt-have-built-in-salts?rq=1) for a better explanation :) – Sebastiano franceschin Mar 26 '16 at 19:46