0

In PHP, I’ve always seen that using dedicated password functions such as “password_verify” is the best method. However, I’m currently working on a website where the original developer basically wrote a query that returns the userId by searching for the username and password hash. If there are results, then the user is logged in.

Can someone help explain to me why the latter is a bad idea? I understand about cryptographic functions being slow to prevent timing attacks. In the flip side, it almost seems to me that querying by username and password hash would be more secure as the query time would end the same as if the user wasn’t valid.

  • You shouldn't be able to search for the password hash based on the user's submitted password attempt. Good encryption is "one-way". Ignore that other developer and write proper code. – mickmackusa Mar 02 '22 at 02:41
  • The basic principle : Do not store plain password or decryptable password in your system. Hence one-way encryption is the preferred method. Imagine a case when your system is hacked and the passwords are revealed to the hacker .... – Ken Lee Mar 02 '22 at 02:44
  • To clarify, the stored password IS still hashed. So the code is hashing the user input and then using that hash for the query. – Will Blanton Mar 02 '22 at 02:45
  • Seemingly related: [Full text search on encrypted data](https://stackoverflow.com/q/22286574/2943403) and [Search encrypted data in Database](https://stackoverflow.com/q/33919894/2943403) and [Best way to search encrypted data inside MySQL](https://stackoverflow.com/q/36655190/2943403) – mickmackusa Mar 02 '22 at 12:16

2 Answers2

0

You cannot query by username and hash for eg. Select * from users where user_id=xx AND password=password_hash

This cannot be done because the user will only pass the plain password not the hash because hash will be created in the system and no user will memorize that hash or even see that hash.

Now your next question why you should use password_verify function , that is because it is more secure since it will only match if password provide by the user is matching the encrypted password stored in database and due to this its almost impossible to crack the encryption

Encrypting password will also prevent leakage of raw passwords in case your system is hacked by some way.

Ashu
  • 1
  • 1
  • 2
0

The reason why one cannot search for a password hash in the database is, that a random salt should be generated for each password and is used for hashing. Without first extracting the salt from the password-hash, one doesn't know the used salt and therefore cannot create a comparable hash (which could be searched for).

If a website can search for passwords hashes, it is an utterly unsecure system, because no salt (and an unappropriate algorithm) was used. If you are interested in a more indepth explanation, you can have a look at my tutorial about secure password storage.

martinstoeckli
  • 23,430
  • 6
  • 56
  • 87