0
votes

I'm having troubles with verifying a password with the password_hash and password_verify functions. For some reason it always returns false.

The hash is stored in a database, when the user provides an email and a password, if a record of a user with the provided email exists, the provided pass and the hash from that user record is verified (which returns false, providing the right password).

The code below is for test purposes because it wasn't working properly in the real context (with data stored in the database)

Here's some of the code.

  <?php
      //create random password with 15 chars
      $pass = generate_random_string(15);
      $hash = password_hash($pass, PASSWORD_BCRYPT);
      var_dump(password_verify($pass, $hash));
      //returns bool(true)

Until this part everything is fine, it creates a pass, hash it and when verified returns true. Now the weird part.

       if (isset($_GET['pass']) &&
           isset($_GET['hash'])) {

            var_dump(password_verify($_GET['pass'], $_GET['hash']));
            //returns bool(false)
       }
   ?>

If I take the previous generated values (pass and hash) and pass them has URL parameters and verify them, it returns false.

What am I doing wrong here?

UPDATE

dumping $_GET array shows the correct parameters and values.

1
You need to provide the password_verify function as well - Derek Pollard
can you also dump the $_GET array - I think you might be assuming something which isn't correct there... - Paul Dixon
Isn't the hash supposed to be stored and used later when the user send the password? - A.L
Ryan Vincent yes, it is correct, this code is just for test purposes. - José Pinto
Going to the trouble of hashing and yet passing them through a query string? - Jay Blanchard

1 Answers

2
votes

Try encoding the values before appending them to the url:

$pass = generate_random_string(15);
$hash = password_hash($pass, PASSWORD_BCRYPT);
var_dump(password_verify($pass, $hash));
$pass_encoded = urlencode($pass); // PASS THIS IN THE URL
$hash_encoded = urlencode($hash); // PASS THIS IN THE URL

And the decode it:

if (isset($_GET['pass']) && isset($_GET['hash'])) {
    var_dump(password_verify(urldecode($_GET['pass']), urldecode($_GET['hash'])));
}