3

I am attempting to hash a password before I store it in a user database, so I run the code:

$hashedPass = password_hash($pass, PASSWORD_DEFAULT); 

This code gives me a value, say $2y$10$wAJr0Z1spRtOcK4cLhIkguUCKgwZKYrwm.nRhm6AtCfDH8ri7ylJu which are stored in the database. Now when I attempt to log in, the same string put in as a password gives a completely different $hashedPass: say $2y$10$cayCQDSQ6pCICSozuIgBNu9uIopIoT5R6Y7aHXG6wx4v/oKx.Ipse

Is this just random? Is there something I should use instead?

3

1 Answer 1

5

This is the expected behavior. password_hash generates a salt which is used along with the plaintext password to generate a hash. The salt is generated randomly so the output will be different each time you call password_hash.

Use password_verify to verify passwords.

http://php.net/manual/en/function.password-verify.php

All of the information necessary for password_verify to verify a plaintext password is contained in the hash itself. The anatomy of a hash depends on the algorithm used, for the password hash you provided:

$2y$10$wAJr0Z1spRtOcK4cLhIkguUCKgwZKYrwm.nRhm6AtCfDH8ri7ylJu 
  • $2y$ This prefix indicates that this is a bcrypt hash
  • 10 This is the cost parameter
  • wAJr0Z1spRtOcK4cLhIkgu The first 22 character is the salt
  • UCKgwZKYrwm.nRhm6AtCfDH8ri7ylJu The remaining 31 characters is the hash

https://en.wikipedia.org/wiki/Bcrypt

Sign up to request clarification or add additional context in comments.

3 Comments

Note for completeness: The random salt plus some other data is prefixed to the hashed data so that password_verify can generate the same hash for comparison.
Can I run password_verify with both params as hashed passwords? In the example on php.net, only one of the passwords is hashed
Oh wait. . .I just figured out that there is no reason to hash the password if it isn't saved. Sorry

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.