Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
488 views
in Technique[技术] by (71.8m points)

php - Password is not verified using function password_verify

I think i have hashed password using function PASSWORD directly from mysql database(am i doing wrong here?). And i am trying to verify that password with this code:

    if($submit)
    {
        $first=$_POST['first'];
        $password=$_POST['password'];
        $hash="*85955899FF0A8CDC2CC36745267ABA38EAD1D28"; //this is the hashed password i got by using function PASSWORD in database
        $password=password_verify($password,$hash);
        $db = new mysqli("localhost", "root","","learndb");
        $sql = "select * from admin where username = '" . $first . "' and password = '". $password . "'";
        $result = $db->query($sql);
        $result=mysqli_num_rows($result);


        if($result>0)
    {

        session_start();
        $_SESSION['logged_in'] = true;
        session_regenerate_id(true);
        header("Location:loginhome.php");

    }
}

But the password is not matching. What am i missing here?

UPDATE:

After all the suggestions i have used password_hash from php code to store into database.

$db = new mysqli("localhost", "root","","learndb");
$password=password_hash('ChRisJoRdAn123',PASSWORD_DEFAULT);
$sql="INSERT INTO admin (username,password)values('ChrisJordan','$password')";
$db->query($sql);

still the password is not matching.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One cannot search for a salted password hash in a database. To calculate the hash you need the password_hash() function as you already did correctly in your insert statement.

// Hash a new password for storing in the database.
// The function automatically generates a cryptographically safe salt.
$hashToStoreInDb = password_hash($password, PASSWORD_DEFAULT);

To check a password, you first need to search by username only (used a prepared query to avoid sql injection):

$sql = 'select * from admin where username = ?';
$db->prepare($sql);
$db->bind_param('s', $first);

When you finally got the stored hash from the database, it can be checked like this:

// Check if the hash of the entered login password, matches the stored hash.
// The salt and the cost factor will be extracted from $existingHashFromDb.
$isPasswordCorrect = password_verify($password, $existingHashFromDb);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...