PHP密码验证与PDO准备语句错误

时间:2014-02-06 23:59:52

标签: php pdo crypt

抱歉 [重复] 。我花了一天时间,找不到解决方案。我遇到了隐藏(验证)的问题,这是我的代码:

    function generateHash($password, $round=10){
          $salt=substr(base64_encode(openssl_random_pseudo_bytes(17)),0,22);
          $salt=str_replace("+",".",$salt);
          $param='$'.implode('$',array(
               "2y",
                str_pad($round,2,"0",STR_PAD_LEFT),
                $salt
                )
          );
          return crypt($password,$param);
    }


//NOW I INSERT HASH TO DB
    $input = "abc";
    $hashed = generateHash($input);

    $createAccount=$db->prepare("INSERT INTO account ....
    ':secret'   => $hashed;
    .....));    // Until here, no problem, $hashed can be inserted correctely into my db (password, Varchar (64)

现在注册后,用户喜欢登录,这是问题所在。首先,我正在检查,看看我是否做得很好

    $input = "abc";
    $forCheck = "abc";
    $hashedHash = generateHash($input);

    if (crypt($forCheck, $hashedHash) == $hashedHash) {
        echo "MATCH";
    }else {
        echo "NOT MATCH";
    }
    // OUTPUT: "MATCH"

问题在于:

    $check=$db->prepare("SELECT id, password FROM account WHERE email = :email ");
    $check->execute(array(
        ':email' => $user
        )
    );
    if ($check->rowCount() <= 0) {
         echo "You are not registered";
    }else {
         $sRow=$check->fetchAll(PDO::FETCH_ASSOC);
         foreach ($sRow as $row) {
              $hashedHash = generateHash($row['password']);

              if (crypt($input, $hashedHash) == $hashedHash) {
                    echo "Passwords Matched";
              }else {
                    echo "Passwords did not match";
              }
          }
      }
      // OUTPUT: "Passwords did not match"

请帮忙吗?

1 个答案:

答案 0 :(得分:0)

问题出在这里......

$hashedHash = generateHash($row['password']);

您没有存储纯文本密码,为什么要再次通过generateHash传递哈希?应该只是

if (crypt($input, $row['password']) == $row['password'])

我也借此机会清理你的查询逻辑。首先,PDOStatement::rowCount应该

$check = $db->prepare('SELECT id, password FROM account WHERE email = :email LIMIT 1');
$check->execute([':email' => $user]);
if ($row = $check->fetch(PDO::FETCH_ASSOC)) {
    if (crypt($input, $row['password']) == $row['password']) {
        echo 'Passwords Matched';
    } else {
        echo 'Password did not match';
    }
} else {
    echo 'You are not registered';
}