Blowfish加密-已创建哈希,但不会进行验证


Blowfish encryption - hash is created but will not verify

我不久前写了这段代码,现在我正在为一个新项目恢复它,但它似乎不起作用,我一生都无法弄清楚为什么它不会验证哈希。

当注册第一个passwordEncrypt()函数时,运行的2个函数如下。

当尝试登录时,会调用checkPassword()函数,而不是登录并回显"yes",它会到达回显"no"的部分。

所以,如果一双新鲜的眼睛能看一眼,请提前感谢!

// Encrypt user password
function passwordEncrypt($password) {
    // set the salt
    $salt = substr(md5(time()), 0, 22);
    // encrypt using blowfish with a load of 10
    $password = crypt($password, '$2a$10$' . $salt);
    // return the encrypted hash
    return $password;
}
/*
    Check password function when logging in
    first we select the password from the supplied username from the database
    // get the row and set the hash to the currect password from the database
    //run the salts etc and check to see if the passwords match
*/
function checkPassword($userName, $password, $db){
    $sql = 'SELECT password FROM users WHERE userName = :userName';
    $stmt = $db->prepare($sql);
    $stmt->bindValue(':userName', $userName, PDO::PARAM_STR);
    $stmt->execute();
    $numRows = $stmt->rowCount();
    if ($numRows > 0) {
        $row = $stmt->fetch();
        $hash = $row['password'];
        // run the hash function on $password 
        $fullSalt = substr($hash, 0, 29); 
        $new_hash = crypt($password, $fullSalt); 
        // Check that the password matches
        if($hash == $new_hash) {
            echo 'yes';
            exit;
            return true;
        } else {
            echo 'no';
            exit;
            return false;
        }
    } else {
        echo 'way';
        exit;
        return false;
    }
}

我注册了一个密码,然后尝试了一下,这就是它返回的

密码:$2a$10$023d3086e8462207a1secueWH4Ub40MWbQJ7F9输入:$2a$10$023d3086e8462207a1ecueWH4Ub40MWbQJ7F9hapWU3lYxlg3AAa无

所以它在hapWU3lYxlg3AAa 上添加

"列长度是多少?40?50?60?其他?$2a$10$023d3086e8462207a1secueWH4Ub40MWbQJ7F9表示太短。–Fred-ii-"

"数据库中的ah 45–Tom C"

给你。该列的长度太短,需要为60。

手册建议使用255。
轻微更正:255是password_hash()上的手册建议使用的。然而,最好实际使用255,手册还建议在未来牢记这一点,并认为这是"一个不错的选择"

您需要清除行,将列更改为60或更大,然后创建一个新的哈希并再次登录。

2a加元10加元023d3086e8462207a1安全WH4Ub40MWbQJ7F9hapWU3lYxlg3AAa

是60长


脚注:

有人说,有些人发现使用crypt()、使用password_hash()或兼容包(如果PHP<5.5)很难工作https://github.com/ircmaxell/password_compat/实际上更容易选择权在你。

请参阅此问答;A也在堆栈上:

  • PHP crypt()的输出长度是多少