Search code examples
phpencryptionpasswordspassword-hash

password_verify shows invalid password in function


I am trying to work with passrord_hash() and password_verify(). The below code works perfect.

$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.';
}

but when I convert it to function, it shows invalid password. I echoed the passing values in the functions. It shows the right value. But the result turns wrong. I can't understand what is wrong with the code

$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 />';
}
}

Please help


Solution

  • 1 . Loop uses const value of password

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

    2 . Loop uses variable $pass and and puts varialbe to $pass. On the second circle variable $pass contains hash, but not the password.

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