Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I decrypt a password hash in PHP?

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?

like image 454
dariodp Avatar asked Jun 03 '14 20:06

dariodp


People also ask

Can I decrypt password hash?

How to decrypt a hash? The principle of hashing is not to be reversible, there is no decryption algorithm, that's why it is used for storing passwords: it is stored encrypted and not unhashable.

Can we decrypt MD5 in PHP?

How to Decrypt MD5 Passwords in PHP? The MD5 cryptographic algorithm is not reversible i.e. We cannot decrypt a hash value created by the MD5 to get the input back to its original value. So there is no way to decrypt an MD5 password.

How can I get encrypted password in PHP?

Decryption of the password: To decrypt a password hash and retrieve the original string, we use the password_verify() function. The password_verify() function verifies that the given hash matches the given password, generated by the password_hash() function.


1 Answers

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.

like image 135
Gergo Erdosi Avatar answered Oct 31 '22 16:10

Gergo Erdosi