简体   繁体   中英

In PHP how to check if hashed password match database password

my problem is in the login page when the user login I get this error the sha256 function is not implement in mysql. Is there something wrong with my code or is is the sha2 not supported anymore. Is there other way to hash password in mysql.

Warning: hash(): Unknown hashing algorithm: sha2

create_account.php

//create account 
 $query = "INSERT INTO mytable (username,fname,lname,country,age,gender,password)
    VALUES ('$username','$fname','$lname','$country',$age','$gender',SHA2('$password', 224))";

login.php

//check if password match 
$hased_password= hash("sha2", $password);
$hased_password= mysqli_real_escape_string($conn,$hashedPass);

  $query = mysqli_query($conn,"select * from mytable where password=  '$hased_password'  AND username='$username'");

 $rows = mysqli_num_rows($query);
if ($rows == 1) {
$_SESSION['username']=$username;  
$_SESSION['fname'] = $fname;
header("location: userPage.php");  
} else {
$error = "username or password is invalid";
}
mysqli_close($conn);

I give the following answer with the best of intentions.

. . .

I would direct your attention here PHP: Password Hashing Functions

and ...

I would direct your attention here PHP Manual: PDO Prepared Statements

My advice would be to use nothing less than Blowfish for hashing your passwords. Also, you need to be conscious of timing attacks. Hence, just letting the database tell you whether or not a hashed password matches is an answer, but it is a poor answer, as failed attempts that are close can be measured in micro-seconds (especially since the Internet / network lies between the attacker and your system). The longer it takes to get the result back, the closer the attacking system knows (assumes) it is to having the correct hash.

(Remember, a string comparison goes character by character. It does not matter what the contents of the string are).

Attacks during an off peak time might yield the best results.

Use PDO prepared statements.

Use password_verify, inside the business logic layer to determine if the hashes match. Only use the database to retrieve a hash. Don't do business logic tasks at the data layer. Do not rely on a count of records. That is a short cut.

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