dariodp dariodp - 4 years ago 123
PHP Question

How can I decrypt a password hash in PHP?

I need to decrypt a password. The password is crypted 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 crypted 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 crypted, 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?

Answer Source

Bcrypt is a one-way hashing algorithm, you can't decrypt hashes. Use password_verify to check whether a password matches the stored hash:

// 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="'.$username.'"';

And do the password validation in PHP using a code that is similar to the example above.

Edit: Constructing the query this way is very dangerous. If you don't escape the input properly, the code will be vulnerable to SQL injection attacks. See this SO answer on how to prevent SQL injection.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download