Why is a hash in Bcrypt different each time it is encrypted? Correct way to compare passwords in Bcrypt

Asked

Viewed 132 times

1

Good,

I am trying to create a webpanel and a friend suggested me to encrypt users' passwords with BCRYPT for their security.

My problem when trying to sign in, the encrypted password that is stored in the database is different from the one sent in the SQL request.

For example, this is the main part of my code to validate the user credentials:

File: passwordEncryptor.php

<?php
function passwordEncryptor($password){
$options = [
        'cost' => 14,
    ];
    return password_hash($password, PASSWORD_BCRYPT, $options);
}

?>

File: login.php

<?php
    $email = mysqli_real_escape_string($dbcon, $_POST['email']);

    $query = "SELECT * FROM pcd_users WHERE email='$email'";
    $do_query = @mysqli_query($dbcon, $query);
    if($do_query){
        if(mysqli_num_rows($do_query) != 1){
            $errors[] = "E-mail ou Palavra-Passe incorretos.";
        }else{
            while ($row = mysqli_fetch_array($do_query, MYSQLI_ASSOC)) {
                if(pasword_verify($_POST['password'], $row['password']){
                    mysqli_free_result($do_query);
                    session_start();
                    $_SESSION['userNum'] = $row['num'];
                    header("Location: ./page.php");
                    exit();
                }else{
                    $errors[] = "E-mail ou Palavra-Passe incorretos.";
                }
            }
        }
    }else{
        $errors[] = "Erro: " . mysqli_error($do_query);
    }
    mysqli_free_result($do_query);
?>

Assuming that the password stored in the database that was overwritten using the same function (passwordEncryptor) is 1234, that is to say $2y$14$gyyo5OaMe4SeXIhRStbdjOnZZrb3IOdCoIOQlzPZj15MhGBHUjniq, why at the time of authentication the hash sent is $2y$14$O6iOBsAyv0JqwGudQhKPB.f68nLthfoMlJUU8n8zRuXxFJubhe7CO

Edit

After a little more research on the mother site, I found the correct form to verify that the password entered is equal to the encrypted one in the database.

For Andrew Moore in reply

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

But still the question remains: Why is it that every time a string hash is made in bcrypt, the same is different?

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.