Search code examples
phpmysqliblowfish

How can I read an encrypted password from the database to allow users access?


I am unable to match the password returned by the crypt() function to allow users access.

My cryptPassword function:

function cryptPass($input, $rounds = 9) {
    $salt = '';
    $saltChars = array_merge(range('A', 'Z'), range('a', 'z'), range(0, 9));
    for ($i = 0; $i < 22; $i++) {
        $salt .= $saltChars[array_rand($saltChars)];
    }
    return crypt($input, sprintf('$2y$%02d$', $rounds) . $salt);
}

My registration form:

if($_POST['register']) { 
    if($_POST['username'] && $_POST['email'] && $_POST['password']) {
        $username = mysqli_real_escape_string($dbCon, $_POST['username']);
        $email = mysqli_real_escape_string($dbCon, $_POST['email']);
        $password = mysqli_real_escape_string($dbCon, cryptPass($_POST['password']));
         // insert into databse...
    }
}

My login form:

if($_POST['username'] && $_POST['password']) {  
    $username = mysqli_real_escape_string($dbCon, $_POST['username']);
    $inputPassword = mysqli_real_escape_string($dbCon, $_POST['password']);
    $password = "SELECT * FROM users WHERE password = '$inputPassword'";
    $hashedPass = cryptPass($password);
    if(crypt($inputPassword, $hashedPass) == $hashedPass) {
        die("<br>Password is a match. Log in");
    } else {
        echo "<br>Passwords do not match!!! Do NOT log user in <br>";
    }
}

I have tested to see why I am unable to log the users in, these are the results:

  • user name: 2, password: 2 - logging in -> results ->

Passwords do not match!!! Do NOT log user in:

$inputPassword = 2
$query password = SELECT * FROM users WHERE password = '2'
$hashedPass = $2y$09$ICAfpjSJyXEp93JsUbhyieaeMX7KNC6vQSayc0nT6QLHWrMjdYQhi
crypt($inputPassword, $hashedPass) = $2y$09$ICAfpjSJyXEp93JsUbhyie9dqXeWEVqCYGR3faLHveUp1LsJegxpu

As you can see, the first part is identical ($2y$09$ICAfpjSJyXEp93JsUbhyie), however the other part is constantly changing. I believe it has to do with the $salt I'm adding? If so, how can I match the passwords to allow access to my users?


Solution

  • Check out hash_equals. Also, here is an article on the implementation.