How to verify password against database?

I went through many articles related to this topic, such as this:

Using PHP 5.5’s password_hash and password_verify function

Yet, I’m unsure if I’m hashing and salting the correct way or over doing it!

I want to use my own salt and then hash. Both salt and hashed password stored in the database in two different fields.

This is how I hash the password before storing into database

$cost = 10;
$salt = strtr(base64_encode(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM)), '+', '.');
$salt = sprintf("$2a$%02d$", $cost) . $salt;

//shall I remove this line and replace below PASSWORD_DEFAULT  with PASSWORD_BCRYPT instead?
$password = crypt($data['password'], $salt);

$hash = password_hash($password, PASSWORD_DEFAULT);

Given that, I’m trying to verify the password as below: Somehow I feel that I’m complicating the process.

$salt=$row['salt'];//taken from db
$hashAndSalt=$row['hashpword'];//taken from db
$password="pwtester";//user keyed in password

$newpassword = crypt($password, $salt);
$newhash = password_hash($newpassword, PASSWORD_DEFAULT);


if (password_verify($password, $newhash)) {
   echo"verified";
}
else
{
    echo"Not verified"; 
}

EDITED:

Now I store like this:

$cost = 10;
$salt = strtr(base64_encode(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM)), '+', '.');
$options = array('cost' => $cost,'salt' => $salt);
$hash = password_hash($data['password'], PASSWORD_DEFAULT,$options);

But verification confusing:

$email = "[email protected]";
$uid= '555ca83664caf';
$sql = "SELECT *FROM authsessions WHERE email =:myemail AND useruuid =:uid";

$statement = $pdo->prepare($sql);
$statement->bindValue(':myemail', $email);
$statement->bindValue(':uid', $uid);
$statement->execute();
while( $row = $statement->fetch()) {
    echo "salt ".$row['salt']."<br/><br/>";
    echo "hashpassword ".$row['hashpword'];
}

$salt=$row['salt'];
$hashAndSalt=$row['hashpword'];
$password="test55";

$newhash = password_hash($password+$salt, PASSWORD_DEFAULT);


if (password_verify($newhash, $hashAndSalt)) {
   echo"verified";
}
else
{
    echo"Not verified"; 
}

It echoes “Not Verified”

Leave a Comment