How can I decrypt a password hash in PHP?
encryption, mysql, php
Solution
Bcrypt is a one-way hashing algorithm, you can't decrypt hashes. Use password_verify to check whether a password matches the stored hash:
<?php
// See the password_hash() example to see where this came from.
$hash = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';
if (password_verify('rasmuslerdorf', $hash)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
In your case, run the SQL query using only the username:
$sql_script = 'SELECT * FROM USERS WHERE username=?';
And do the password validation in PHP using a code that is similar to the example above.
The way you are constructing the query is very dangerous. If you don't parameterize the input properly, the code will be vulnerable to SQL injection attacks. See this Stack Overflow answer on how to prevent SQL injection.
Problem
I need to decrypt a password. The password is encrypted with `password_hash` function. ``` $password = 'examplepassword'; $crypted = password_hash($password, PASSWORD_DEFAULT); ``` Now, let's assume that `$crypted` is stored in a database (there's a "users" table, with usernames, passwords, etc) and I need to do a login: I have to see if the password entered by the user matches the encrypted password stored in the database. This is the sql code... ``` $sql_script = 'select * from USERS where username="'.$username.'" and password="'.$inputpassword.'"'; ``` ...but `$inputpassword` is not encrypted, so it's not equal to what is stored in the password field of the table users... So, there's a function to decrypt after the use of `password_hash`? Or should I change my encrypt method? Or what else?