Bcrypt,你如何使用随机盐进行验证?

Bcrypt, how do you verify with the random salt?

我从 PHP 网站上获得了这段代码。我可以在没有盐的情况下完成这项工作。但是你如何用盐来验证——或者它是否必须存储在一个变量中然后你以后使用它?不确定如何进行下一步验证。很多关于如何制作散列的教程,但验证是另一回事。谢谢。

$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 = 'y$nJp/w0OC41I0m44T9OQKBuWUrQi63PrJuvDc68KI6oDBdnZK01kiW ';

if (password_verify('rasmuslerdorf', $hash)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}

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.

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

只需像上面那样使用函数,它会自动检测盐分。

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

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

即使您不加盐,password_hash 也会自动添加一个随机生成的盐,因此您验证已加盐的密码应该没有任何问题。

另请注意:

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.