Search code examples
phpmysqldatabasepasswordsbcrypt

password_hash seems to return a random variable


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?


Solution

  • 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