简体   繁体   中英

PHP crypt validation with PDO prepared statement Error

and sorry for the [duplicate] . i spent a day, not able to find a solution. I am having a problem with crypt (validation) , here is my code:

    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)

Now after registration, user likes to login, here is the problem. First, i'm checking, to see, if i did well the function

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

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

The problem is here:

    $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"

Any help please ?

The problem is here...

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

You aren't storing a plain text password so why would you pass the hash through generateHash again? Should simply be

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

I'd also take this opportunity to clean up your query logic. For one thing, PDOStatement::rowCount should not be relied upon.

$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';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM