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?

  • 2
    `password_verify`. – tkausl Dec 17 '17 at 01:26
  • only for completeness the link to [passoword_verify](http://php.net/manual/en/function.password-verify.php): http://php.net/manual/en/function.password-verify.php – Jeff Dec 17 '17 at 01:30
  • The results and how to use it is stated in the return value of the manual for the function: http://php.net/manual/en/function.password-hash.php#refsect1-function.password-hash-returnvalues – Will B. Dec 17 '17 at 03:26

1 Answers1

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

Mathew Tinsley
  • 6,805
  • 2
  • 27
  • 37
  • 2
    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. – zaph Dec 17 '17 at 02:47
  • Can I run password_verify with both params as hashed passwords? In the example on php.net, only one of the passwords is hashed – Ian Whitehouse Dec 17 '17 at 15:18
  • Oh wait. . .I just figured out that there is no reason to hash the password if it isn't saved. Sorry – Ian Whitehouse Dec 17 '17 at 15:19