如何从数据库中读取加密密码以允许用户访问?

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

我无法匹配 crypt() 函数返回的密码以允许用户访问。

我的 cryptPassword 函数:

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('y$%02d$', $rounds) . $salt);
}

我的注册表:

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...
    }
}

我的登录表单:

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>";
    }
}

我已经测试过为什么我无法登录用户,结果如下:

密码不匹配!!!不要登录用户:

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

如您所见,第一部分是相同的 ($2y$09$ICAfpjSJyXEp93JsUbhyie),但另一部分在不断变化。我相信这与我添加的 $salt 有关?如果是这样,我如何匹配密码以允许访问我的用户?

查看 hash_equals. Also, here 一篇关于实现的文章。