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

时间:2015-07-29 19:34:15

标签: php mysqli blowfish

我无法匹配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('$2y$%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>";
    }
}

我已经测试了为什么我无法记录用户,这些是结果:

  • 用户名:2,密码:2 - 登录 - &gt;结果 - &gt;

密码不匹配!!!请勿将用户登录:

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

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

1 个答案:

答案 0 :(得分:0)

结帐hash_equals。另外,here是关于实施的文章。