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 :)
As in the comments is already suggested, the best way is to use password_hash()
instead of using:
$cost = 10;
$salt = strtr(base64_encode(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM)), '+', '.');
$salt = sprintf("$2a$%02d$", $cost) . $salt;
$hash = crypt($password, $salt);
In my case, my php version was under 5.5, and I haven't been able to insert the library compatible with lower versions, even if it is the safest way!!
In order to check if my password stored was the same as the one the user inputs via $_POST
, the if has to be modified as follows:
if (crypt($password, $hash) == $hash) {
...
and this did the trick!! Take into account that I'm just a begginer, and this method can be unsafe :)