password_verify

(PHP 5 >= 5.5.0, PHP 7)

password_verify验证密码是否和哈希匹配

说明

boolean password_verify ( string $password , string $hash )

验证密码是否和指定的哈希值匹配。

注意 password_hash() 返回的哈希包含了算法、 cost 和盐值。 因此,所有需要的信息都包含内。使得验证函数不需要储存额外盐值等信息即可验证哈希。

时序攻击(timing attacks)对此函数不起作用。

参数

password

用户的密码。

hash

一个由 password_hash() 创建的散列值。

返回值

如果密码和哈希匹配则返回 TRUE,否则返回 FALSE

范例

Example #1 password_verify() 例子

<?php
// 想知道以下字符从哪里来,可参见 password_hash() 的例子
$hash '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';

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

以上例程会输出:

Password is valid!

参见

User Contributed Notes

gorgonz at web dot de 18-Sep-2017 06:53
just the correct link to the wikipedia, seen in the note of "suit at rebell dot at":

https://en.wikipedia.org/wiki/Crypt_(C)
chris at weeone dot de 14-Jan-2016 09:09
The function password_verify() uses constant time. This makes it safe against timing attacks. Don't use crypt($password_database) === crypt($password_given_by_login), since there is no protection against timing attacks!

If you don't want to use password_verify(), then have a look at hash_equals(), which also runs a timing attack safe string comparison.
Anonymous 29-May-2014 10:40
If you get incorrect false responses from password_verify when manually including the hash variable (eg. for testing) and you know it should be correct, make sure you are enclosing the hash variable in single quotes (') and not double quotes (").

PHP parses anything that starts with a $ inside double quotes as a variable:

<?php
// this will result in 'Invalid Password' as the hash is parsed into 3 variables of
// $2y, $07 and $BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq
// due to it being enclosed inside double quotes
$hash = "$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq";

// this will result in 'Password is valid' as variables are not parsed inside single quotes
$hash = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';

if (
password_verify('rasmuslerdorf', $hash)) {
    echo
'Password is valid!';
} else {
    echo
'Invalid password.';
}
?>
suit at rebell dot at 19-Oct-2013 04:18
As Vasil Toshkov stated, password_verify() can be used to verify a password created by crypt() or password_hash()

That is because passwords created by password_hash() also use the C crypt sheme

If you want to verify older plain MD5-Hashes you just need to prefix them with $1$

See https://en.wikipedia.org/wiki/Crypt_(C) for more information.
Vasil Toshkov 13-Oct-2013 06:16
This function can be used to verify hashes created with other functions like crypt(). For example:

<?php

$hash
= '$1$toHVx1uW$KIvW9yGZZSU/1YOidHeqJ/';

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

// Output: Password is valid!

?>