Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

password_hash, password_verify, MySQL misunderstanding?

I can't seem to get this test to display the hashed password from the database. It displays the password from the form just fine. Trying to do this test to figure out why I can't get it to verify the password from the form compared to the password stored in the database. I read something about escaping the $ signs that are within the hash but I'm not sure on how to do that with the code I'm working with. Either way, something isn't right. Any help would be GREATLY appreciated!

require('../connect.php');
$username = $_POST['username-sign-in'];
$password = $_POST['password-sign-in'];
$hashedpassword = password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);
if (empty($username)) {
    echo 'Please enter your username.';
    exit();
}
if (empty($password)) {
    echo 'Please enter your password.';
    exit();
}
if (isset($username, $password)) {
    $getuser = $connection->prepare('SELECT `username`, `password` FROM `users` WHERE `username` = ? AND `password` = ?');
    $getuser->bind_param('ss', $username, $hashedpassword);
    $getuser->execute();
    $userdata = $getuser->get_result();
    $row = $userdata->fetch_array(MYSQLI_ASSOC);
    echo 'Password from form: ' . $hashedpassword . '<br />';
    echo 'Password from DB: ' . $row['password'] . '<br />';
    if (password_verify($row['password'], $hashedpassword)) {
        echo 'Success.';
        exit();
    }
    else {
        echo 'Fail.';
        exit();
    }
}
else {
    echo 'Please enter your username and password.';
    $connection->close();
    exit();
}
like image 901
slicksct Avatar asked Jan 12 '14 01:01

slicksct


1 Answers

You can't hash the input and then query against that in the database, as the hash will use a different random salt each time. So you could hash the same password a thousand times and get 1000 different results.

You need to simply just query the DB for the record related to the username, then compare the password hash returned from the DB with the input password using password_verify().

Also, when initially writing the hash to the DB on password creation (using password_hash()) there is no need to escape the hash. password_hash() is not used at all in the password verification process.

like image 87
Mike Brant Avatar answered Sep 20 '22 14:09

Mike Brant