【问题标题】:Why isn't the matching of this hash happening?为什么这个哈希的匹配没有发生?
【发布时间】:2016-07-04 15:54:38
【问题描述】:

我正在使用 PHP 5.4 版,我已经四处寻找哈希机制,但我无法让它工作。棘手的部分是用用户尝试的另一个密码验证散列密码,我在这里做错了什么?

  //and yes I am using password as name in this example

 $password_entered ="cucumberball";
    $password_hash = crypt($password_entered);

mysql_set_charset('utf8');
pdoConnect();

//insert hashed pass (same name and pass(hashed) for user)
$stmt = $pdo->prepare("insert into user (name,password) values (:name,:password)");
    $stmt->bindParam(':name', $password_entered);
    $stmt->bindParam(':password', $password_hash);
    $stmt->execute();

    //retriving password from db and checking if its correct with the login password provided
    $stmt = $pdo->prepare("select password from user where name = :name LIMIT 1;");
    $stmt->bindParam(':name', $password_entered);
    $stmt->execute();

    $user = $stmt->fetch(PDO::FETCH_OBJ);

     if(crypt($password_entered, $password_hash) == $user->password) {
        // password is correct
        echo "WORKS";
    }else{

        echo "did not work";
    }

【问题讨论】:

  • 旁注:您正在将未加密的密码作为名称保存在数据库中...
  • 我将输入的密码保存为名称。仅作为示例
  • This example 工作:从它开始(或使用它)
  • @bmcculley 的回答也是一个好点。一个建议:在之前用简单的文本检查你的密码系统(评论所有关于 db 的部分)。当您的密码检查有效时,添加 tha db 的东西。
  • 好的,谢谢,会检查一下。

标签: php sql hash passwords


【解决方案1】:

当您进行比较时,您在加密密码时会加盐,而数据库中的密码仅被加密。

if(crypt($password_entered, $password_hash) == $user->password) {

另外,根据文档,您应该像这样比较

您应该将 crypt() 的全部结果作为盐传递给 比较密码,以避免不同哈希时出现问题 使用算法。 (如上所述,标准的基于 DES 的密码 散列使​​用 2 个字符的盐,但基于 MD5 的散列使用 12。)

if (hash_equals($hashed_password, crypt($user_input, $hashed_password))) {
   echo "Password verified!";

【讨论】:

    【解决方案2】:

    修正这个 if 语句:

    if(hash_equals(crypt($password_entered, $password_hash), $password_hash))
    {
        echo "WORKS";
    }
    

    或者因为 PHP 5.4 中没有 hash_equals

    if(crypt($password_entered, $password_hash) == $password_hash)
    {
        echo "WORKS";
    }
    

    但如果没有hash_equals,您的哈希值很容易受到timing attack 的攻击。

    您可能还想阅读this manual

    【讨论】:

    • @Christopher 为什么需要详细说明“阅读this manual”?
    • 没看到那个链接
    • @fusion3k 你认为 == 代替 hash_equals 做这项工作吗?
    • @Saibot 是的,是
    猜你喜欢
    • 2012-07-22
    • 2010-10-11
    • 1970-01-01
    • 1970-01-01
    • 2011-03-27
    • 2021-04-25
    • 1970-01-01
    • 1970-01-01
    • 2015-12-04
    相关资源
    最近更新 更多