blah blah
blah blah

Reputation: 15

hashing and salt not comparing correctly

I have successfully gotten the salted hash saved into the database. Now the problem i'm facing is exactly how to set it up to compare between them to login in. Do i have to make the hash again? and if i do make it again won't it be different? Right now the check says it works but i cannot sign with the password before it was hashed.
the code below is what ive tried so far:

$con = mysqli_connect($DB_HOST,$DB_USER,$DB_PASSWORD,$DB_DATABASE);
if(!$con){
echo "Connection Error...".mysqli_connect_error();
}
else
{
//echo "Database connection Success...";
}

 $user_name =mysqli_real_escape_string($con, $_POST["login_name"]);  
 $user_pass =mysqli_real_escape_string($con, $_POST["login_pass"]);  
$cost = 10;
$salt = strtr(base64_encode(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM)), '+',  '.');
$salt = sprintf("$2a$%02d$", $cost) . $salt;


 $sql_query = "select  user_name,user_pass from user_info where  
user_pass ='$user_pass' and user_name = '$user_name'";  


$hash = crypt($user_pass, $salt);
if(crypt($user_pass,$hash)==$hash){
echo "works"; 
 $result = mysqli_query($con,$sql_query);  
 if(mysqli_num_rows($result) >0 )  
 {  
 $row = mysqli_fetch_assoc($result);  
 $name = $row["name"];  
 echo "Login Success..Welcome " .$name;
 }  
 else  
 {   
 echo "Login Failed.......Try Again..";  

}
}

Upvotes: 1

Views: 93

Answers (1)

BeetleJuice
BeetleJuice

Reputation: 40886

Your login will always fail because this query...

"select  user_name,user_pass from user_info where  
user_pass ='$user_pass' and user_name = '$user_name'"

... compares the user's entered password to the hashed stored password.

The better approach is:

  1. SELECT record with the login username (ignoring password)
  2. If no record is found, the username doesn't exist. Fail
  3. Compare the password in that record with the password that was submitted.
  4. If they don't match, the password is wrong. Fail.
  5. Login successful.

You're making your life really difficult by trying to implement your own hashing when PHP provides this natively. To hash password at account registration (suppose user chose $clear_pwd):

$hash_pwd = password_hash($clear_pwd, PASSWORD_DEFAULT);

This generates a cryptographically secure salt and hash for you. $hash_pwd gets stored in the DB. Now at login, on step 3 above (password verification), do:

if (password_verify($clear_pwd, $hash_pwd)){ 
    // $clear_pwd is correct
}else{
    // password is incorrect.
}

Simple!

Upvotes: 2

Related Questions