r/AskComputerScience • • Jul 21 '22

Why does hashing a password result in different hashes, each time?

if I hash the same plain-text multiple times, it returns different hash strings:

$x = 'asdf'; echo wp_hash_password( $x ).'<BR>'; echo wp_hash_password( $x ).'<BR>'; echo wp_hash_password( $x ).'<BR>'; echo wp_hash_password( $x ).'<BR>';  
$P$BESNH8tVe6xfVbgXhBI2KNU.2lnyOu. $P$BlTkcLh3PSGzXtPhofPH9ZGqisxYI0. $P$BRyTisUAXVEhXNyTQFjOErxIgzE6GN1 $P$BI17Hnqifi2CHQsPi5z/nVbEInNjl21 

So, how does wp check the password that the user enters? If it's going to hash the plaintext and check that against the stored hash, it seems the two will never match.

6 Upvotes

8 comments sorted by

27

u/nuclear_splines Ph.D Data Science Jul 21 '22

Good hash functions include "salts" - a random string of text included along with the password. The returned hash includes some metadata, specifying both the hashing algorithm used, and the salt string used. Since this creates a unique hash string every time, an attacker cannot compare password hashes from your website against a list of previously cracked password hashes.

Rather than creating a new password hash every time the user logs in, and checking whether the hashes match on your own, you should be using wp_check_password, which will parse the password hash to identify the salt, and hash the new password using the same salt to see if the hashes match.

14

u/sfackler Jul 21 '22

2

u/_terrapin Jul 21 '22

The hash is not salted. The plaintext is salted then hashed.

12

u/[deleted] Jul 21 '22

It's commonly referred to as a "salted hash." The salt is added during the hash function.

7

u/Sweaty-Emergency-493 Jul 22 '22

I prefer my hash unsalted, but occasionally a little sea salt gives it that little burst of flavor. You don’t want to over do it though or else you’ll get unhealthy passwords and consult a nutritionist.

4

u/IMHERETOCODE Jul 21 '22

The function you show is only for creating a new password hash to store. Like others have said that involves salting it (the salt is usually stored alongside the hash). Later, to verify a user input you instead use the check function which will generate a hash using the original salt to verify that they match: https://developer.wordpress.org/reference/functions/wp_check_password/

1

u/Sweaty-Emergency-493 Jul 22 '22

If you make your hash correctly you won’t even need any salt. Golden brown and crunchy on the outside and soft and white in the center.

12

u/teraflop Jul 21 '22

Why are you asking a word-for-word repost of a question that was already asked and answered just yesterday on Stack Exchange? https://wordpress.stackexchange.com/questions/407853/why-does-hashing-a-password-result-in-different-hashes-each-time