简体   繁体   中英

Bcrypt hash check not working

I have tried using two different wrappers, namely password_compat and Bcrypt , to encrypt my passwords. The hash saves fine but the check comparison never matches.

I use the following code to store the hashed password:

//include ( "Bcrypt.php" );
include ( "password_compat-master/lib/password.php" );

if ( isset ( $_POST["username"] ) and isset ( $_POST["email"] ) and isset ( $_POST["password"] ) )
{

$username = $_POST["username"];
$password = $_POST["password"];
$email = $_POST["email"];

//$hash = Bcrypt::hash( $password );
$hash = password_hash( $password , PASSWORD_BCRYPT ); //password_compat function

$connect = mysqli_connect( "server" , "user", "pass" , "database" );

//Code to generate next database key ($next)

$sql_insert = "INSERT INTO `use_users` (`UserID`,`Username`,`Password`,`EmailAddress`) VALUES('$next','$username','$hash','$email');";
$res_insert = $connect -> query( $sql_insert );

}

And I use the following code to verify the password (I am aware of possible SQL injection!):

//include ( "Bcrypt.php" );
include ( "password_compat-master/lib/password.php" );

if ( isset ( $_POST["username"] ) and isset ( $_POST["password"] ) )
{

$username = $_POST["username"];
$password = $_POST["password"];

$connect = mysqli_connect( "server" , "user", "pass" , "database" );

$sql_verify = "SELECT * FROM `use_users` WHERE `Username`='$username';";
$res_verify = $connect -> query( $sql_verify );

while ( $exe_verify = mysqli_fetch_array( $res_verify ) )
{

$hash = $exe_verify["Password"];

//$check = Bcrypt::check( $password , $hash );
$check = password_verify( $password , $hash ); //password_compat function

if ( $check ) echo "Pass.";
else if ( ! $check ) echo "Fail.";

}

}

When I code my own hash check ( crypt( $password, $hash) ) it returns the same hash as the stored one, but with additional characters appended to it.

What am I doing wrong? Is it a MySQL thing?

I think that your field could store less characters than generated hash length. So hash has been truncated before instert.

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