PHP - Unable to login after password reset with sha512

275 views Asked by At

I'm building a simple login script and I am able to register and login no problem. However I am now trying to add a "Forgotten password" feature and I can't figure out why it's not working.

I am able to update the password in the mysql table using the same sha512 and salting method I use in my registration script but after its updated I can no longer login.

The login function that runs when a user tries to login is as follows:

if ($stmt = $mysqli->prepare("SELECT userID, firstName, pWord, salt FROM users WHERE email = ? AND conf = 1 LIMIT 1")) {
    $stmt->bind_param('s', $email);  // Bind "$email" to parameter.
    $stmt->execute();    // Execute the prepared query.
    $stmt->store_result();
    // get variables from result.
    $stmt->bind_result($user_id, $firstName, $db_password, $salt);
    $stmt->fetch();

    // hash the password with the unique salt.
    $password = hash('sha512', $password . $salt);
    if ($stmt->num_rows == 1) {
            // Check if the password in the database matches 
            // the password the user submitted.
            if ($db_password == $password) {
                ... // Log user in
            }
}
}

The password part of my registration script:

$random_salt = hash('sha512', uniqid(openssl_random_pseudo_bytes(16), TRUE));

    // Create salted password 
    $password = hash('sha512', $password . $random_salt);

    // Insert the new user into the database 
    if ($insert_stmt = $mysqli->prepare("INSERT INTO users (firstName, lastName, email, pWord, salt, accConf, conf) VALUES (?, ?, ?, ?, ?, ?, 0)")) {

        $insert_stmt->bind_param('ssssss', $firstName, $lastName, $email, $password, $random_salt, $confirmation);
        $insert_stmt->execute();
... // Do something }

The password part of my reset script:

$random_salt = hash('sha512', uniqid(openssl_random_pseudo_bytes(16), TRUE));

    // Create salted password 
    $password = hash('sha512', $password . $random_salt);

    // Update the user's password
    if ($update = $mysqli->prepare('UPDATE users SET pWord = ?, salt = ? WHERE email = ?')) {

        $update->bind_param('sss', $password, $random_salt, $email);
        $update->execute();
... //Do something }

I can see that in the database, the password is updating but when I try to login with the new password, my "Invalid login details error is showing up.

Is there a reason that my passwords would not work after updating?

0

There are 0 answers