Decrypting Password Hashes in PHP Using Password_Hash
Question:
How do I decrypt a password hash generated using the PHP password_hash function? The password is stored in a database and needs to be compared to the entered user input.
Answer:
Unlike encryption, hashing is a one-way process. Once a password is hashed using password_hash, it cannot be decrypted back to its original value. Therefore, it is crucial to use password verification instead of decryption.
Password Verification using password_verify:
<code class="php">$hash = password_hash('examplepassword', PASSWORD_DEFAULT); if (password_verify('examplepassword', $hash)) { echo 'Password is valid!'; } else { echo 'Invalid password.'; }</code>
In your login scenario, execute the SQL query using only the username:
<code class="php">$sql_script = 'SELECT * FROM USERS WHERE username=?';</code>
Then, compare the entered password to the stored hash in PHP:
<code class="php">if (password_verify($inputpassword, $fetchedPasswordHashFromDB)) { // Password matches }</code>
Important Note:
Ensure you sanitize user input to prevent SQL injection attacks. Parameterize your queries using prepared statements or database abstraction layers.
The above is the detailed content of Can I Decrypt a Password Hash Generated by PHP\'s `password_hash` Function?. For more information, please follow other related articles on the PHP Chinese website!