password_verify在功能中显示无效密码

时间:2014-05-21 07:06:45

标签: php encryption passwords password-hash

我正在尝试使用passrord_hash()password_verify()。以下代码非常完美。

$timeTarget = 0.2; 
$pass = "";
$cost = 9;
do {
$cost++;
$start = microtime(true);
$pass = password_hash("qwerty", PASSWORD_BCRYPT, ["cost" => $cost]);
    $end = microtime(true);
} while (($end - $start) < $timeTarget);

echo "Appropriate Cost Found: " . $cost . "\n";
echo $pass;


$hash = $pass;

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

但是当我将其转换为功能时,它显示无效的密码。我回应了函数中的传递值。它显示了正确的价值。但结果错了。我无法理解代码的错误

$str = "qwerty";

$enc = encrypt($str);

verify_string($str, $enc);



function encrypt($pass){
$timeTarget = 0.2; 
$cost = 9;
do {
    $cost++;
    $start = microtime(true);
    $pass = password_hash($pass, PASSWORD_BCRYPT, ["cost" => $cost]);
    $end = microtime(true);
} while (($end - $start) < $timeTarget);


echo $pass."<br />";
return $pass;
}

function verify_string($str, $enc){
echo $str." :  ".$enc."<br />";

if (password_verify($str, $enc)) {
    echo 'Password is valid!<br />';
}
    else {
    echo 'Invalid password.<br />';
}
}

请帮忙

1 个答案:

答案 0 :(得分:1)

1。 Loop使用密码的const值

$pass = password_hash("qwerty", PASSWORD_BCRYPT, ["cost" => $cost]);

2。 Loop使用变量$ pass,并将varialbe置于$ pass。在第二个圆上,变量$ pass包含哈希值,但不包含密码。

$pass = password_hash($pass, PASSWORD_BCRYPT, ["cost" => $cost]);