问题
From my understanding so far (at least I think) the password_hash() function generates a hash based on the algorithm in use, cost and the salt. While the password_verify uses the information provided from e.g. password_hash($pass, PASSWORD_BCRYPT, array('cost'=>10))
to check if the retuned value is true or false as it contains all the information necessary for verifying.
I previously used
$SQL_Query = "SELECT * FROM DB_Table WHERE userName = '".$username."'" AND password = $ID;
which would work as they were stored in plain text and could return true whereas logically it won't work this time around.
I have came across similar questions where they use static passwords in explanations such as
<?php
$to_verify = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';
if (password_verify('rasmuslerdorf', $to_verify))
{
echo 'Password is valid!';
} else
{
echo 'Wrong password.';
}
The concept I am having trouble understanding is how one would check the password input against the hashed value if it is stored in a database rather than the being known by the page at that point in time? I recently got help regarding storing the values which was a silly error on my part but I guess this isn't clicking with me as well as I hoped for the moment.
回答1:
Look at the examples for password_hash()
and password_verify()
together.
The hash-string that's produced by password_hash
is self-describing: it incorporates an indication of both the algorithm and the random-salt that was used. password_verify
knows about all this. It knows how to "do the right thing" for passwords both recent and vintage.
Therefore, simply query the database to get the (hashed ...) password for this user. Then, use password_verify()
to see if this hash-value matches this password-value.
You can't query for the user-name AND password
at the same time. Query only for the user-name, get the hashed value, and use password_verify()
to check it.
回答2:
the hash is generated randomly each time
No, the hash is always the same for a given input, salt value and iterations through which the hash algorithm is run (which is controlled by the cost parameter).
The concept I am having trouble understanding is how one would check the password input against the hashed value if it is stored in a database rather than the being known by the page at that point in time?
You would check the password input at login time, using the password provided by the user, and the salt and potentially number of times to apply the hash algorithm associated with that user. Once the password check is successful, use a session or other mechanism to keep the user logged in.
来源:https://stackoverflow.com/questions/30040540/comparing-passwords-to-stored-hash