0

I am getting an Invalid Password error when I try to execute my code. I want to mention that I am using the same PASSWORD_BCRYPT function for signup too. But, when I implement it in the login code I am not getting success. Please tell me what am I doing wrong and help me fix the bug.

Another thing is that I am entering the same/correct password I used during registration for the demo user. Here is the code for login.

if(isset($_POST['login'])){

$user_name = ($_POST['user_name']);
$upassword = password_hash($_POST['password'], PASSWORD_BCRYPT);
$statement = $db->prepare("SELECT user_name, password, status FROM user_registration WHERE user_name = ?");
$statement->bind_param('s', $user_name);
$statement->execute();

$statement->bind_result($user_name, $password, $status);
$row = $statement->fetch(); //fetch DB results

if (!empty($row)) { // checks if the user actually exists(true/false returned)
    
    if (password_verify($upassword, $row['password'])) {
        echo 'Password is valid!';
    } else {
        echo 'Invalid password.';
    }


} else {
    echo "Entered data is invalid."; // User login details entered does not match any in DB
}

$statement->close();
}
Syed Naveed
  • 83
  • 1
  • 10
  • 1
    What is the length of the `password` column, and what value do you get back from `$password` in your code? – Qirel Sep 08 '20 at 06:12
  • @Qirel Length is Varchar (255) – Syed Naveed Sep 08 '20 at 06:16
  • 1
    `password_verify()` takes the unhashed password, and the hashed password to compare. So using `$upassword = password_hash($_POST['password'], PASSWORD_BCRYPT);` means you re-hash the password, which will not match. – Qirel Sep 08 '20 at 06:20
  • @Qirel It seems I'm lost. Can you please rewrite my code so I can compare the hashed password which is stored in the database with the user input. Thanks. – Syed Naveed Sep 08 '20 at 06:28

1 Answers1

3

Is the password stored on your table the hashed version?

The first parameter for verify_password is the plain text password, in your code you're hashing the password and verifying hash on a hash.

See this example from php docs

<?php
// See the password_hash() example to see where this came from.
$hash = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';

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

Change your verify_password line to

password_verify($_POST['password'], $row['password'])

Or don't hash it in the beginning

$upassword = $_POST['password'];
crimson589
  • 1,238
  • 1
  • 20
  • 36
  • The password is stored as "$2y$10$xQnz10jMPYZzt00.zZ8l.OW7cLmhI4lxEpFxDWirRXtxl9mIsJphq" without quotes. Its original value is "00000000" without quotes. So when I try using the password "00000000" I am getting invalid password error. – Syed Naveed Sep 08 '20 at 06:17