I've been reading several posts and trying different techniques to store a password in MySQL. I've decided to use crypt
and salt
and I've been finally able to insert it on my database. The code used is the following:
$cost = 10;
$salt = strtr(base64_encode(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM)), '+', '.');
$salt = sprintf("$2a$%02d$", $cost) . $salt;
$hash = crypt($password, $salt);
$query = "INSERT INTO users_registered(name , password) VALUES('$name', '$hash')";
mysqli_query($con, $query);
The main problem that I've been struggling for hours is how to check if the password I put is the correct... I am sure I'm doing something wrong, but I'm completely new in this field of security, and all the posts I checked haven't worked for me. This is the code I use to check:
$name = mysqli_real_escape_string( $con, $_POST['name'] );
$password = mysqli_real_escape_string( $con,$_POST["password"]);
$query = "SELECT * FROM users_registered where name='$name'";
$result = mysqli_query($con, $query);
$row = mysqli_fetch_assoc($result);
$hash=$row['password'];
if ($hash->hash==crypt($password, $hash->hash)) {
echo "YEEEESSS";
}
else {
echo "What I'm doing wrooooong!";}
The problem comes from the if
, but I'm not sure what I should put :S
Any help would be appreciated :)