0

I was under the impression, based on research, that when hashing a string with the same function, it will always return the same hash. I am running a program and using the password_hash() function in php to hash, but I continuously get a different hash as a result, therefore, when I compare them, it does not work.

Here is the example I am dealing with.

PIN to hash: 1212

Initial Hash is line 1, the other 3 are the following attempts:

$2y$10$5CAoU8snW79.8WpCS3T0Y.6OT4YkSYIlS2LrII8DweMzjTV5JGh2Cnone
$2y$10$SZgvvB7WG.gXB/AUbWeIOO8HnBit6F7fG.My/Pcyi4D0zXgb3/n3G
$2y$10$9b.WTA3r4ZYMHdtGN28.Je1qJ4R3n.1Mac1hD3kl.NleiCPmuZRianone
$2y$10$VEuLdnKUYftcJFtbY2KqJOJLQ4B/spuhRk6zywyTzjko7y4aZBGWunone 

The function that I am using looks like this, and is used in 3 different places, but I didn't think that would affect the result.

        $pin = password_hash($_POST['pin'],PASSWORD_DEFAULT);
tereško
  • 58,060
  • 25
  • 98
  • 150
xcinman
  • 9
  • 2
  • No - your right. It is *supposed* to return a different hash each time because the function uses random salts. You should compare the unedited password with the hash using `password_verify()`. [I explain all of this here](http://jayblanchard.net/proper_password_hashing_with_PHP.html) – Jay Blanchard Apr 06 '20 at 18:08
  • Ok, I will check that out. Do you know how the verify function will work with the hashing occurring in a different php file than where the verification needs to happen? – xcinman Apr 06 '20 at 18:23
  • Have a read of https://stackoverflow.com/questions/30279321/how-to-use-phps-password-hash-to-hash-and-verify-passwords to see how it is intended to work. – Nigel Ren Apr 06 '20 at 18:26
  • Yes - use `password_hash()` to store the hashed password, then retrieve the hash when you need to verify. – Jay Blanchard Apr 06 '20 at 18:30
  • Ok, I am sure this is easy, but this is stumping me. The way the login works is, the user only types a PIN in. no username or anything extra. Given that, how do I identify the hash that is needed to be pulled? – xcinman Apr 06 '20 at 18:39

1 Answers1

0

password_hash() not only hashes the password but salts it as well. The salt is stored within the string. If you use password_verify() on your hashes, they will all check out with the input. If every input gave the same string, a hacker could check a compromised string against a database of known hashes to find the password.

Dejke
  • 168
  • 1
  • 9
  • Do you know how the password_verify() function would work with the hashing occurring in a separate file than the verification? – xcinman Apr 06 '20 at 18:20
  • It would work just as well. All the information needed to verify the hash exists within the string. hash and verify could run on different machines and it would still work. – Dejke Apr 06 '20 at 18:27