Search code examples
phphashpassword-hash

How does the hash match when the salt is generated randomly in password_hash?


How does this hashing decryption works when the salt is generated randomly by default. In my perceptions it seems something like this:

password_hash(random_salt1+pw) != password_hash(random_salt2+pw) 

How does password_verify(random_salt2+pw) knows the original salt to decode when it's generated randomly?

Thank you for reading this.


Solution

  • It reruns the hash routine on the new text (password) using the parameters it placed in the hash and if that matches the old hash BINGO.

    If you look at the output from password_hash() all the parameters are there in the resulting hash

    See example

    echo password_hash("rasmuslerdorf", PASSWORD_DEFAULT);
    echo password_hash("rasmuslerdorf", PASSWORD_ARGON2I);
    echo password_hash("rasmuslerdorf", PASSWORD_ARGON2ID);
    

    RESULTS

    $2y$10$nbX83VUlyVstPCckavcJy.wQ84i8/cmBD/oeDV/zWrHXkuG6t/9fy
    $argon2i$v=19$m=65536,t=4,p=1$QlQ4emNEb1UxR1JiTG5Ddw$vw4HeiM9CEo8c2KNUslpC7qpH9M9Lo+WxBhX0UPp4oo
    $argon2id$v=19$m=65536,t=4,p=1$U1loZThCYWtXcnpYWWV3NA$52eO0Ig9a1/pwqK3NPeNxwQpRuml36pjN2UN5BaGVGo
    

    Notice that even if you use the same password (text string) you will not get the same hash from password_hash(), this is because the salt is randomly generated as part of the hashing process.

    Also password_hash() explicitly says DONT ADD YOUR OWN HASH. It generates a strong hash internally. A much better one that you are likely to create for yourself

    From the manual of all places The used algorithm, cost and salt are returned as part of the hash. Therefore, all information that's needed to verify the hash is included in it. This allows the password_verify() function to verify the hash without needing separate storage for the salt or algorithm information.

    Also from the manual Warning The salt option is deprecated. It is now preferred to simply use the salt that is generated by default. As of PHP 8.0.0, an explicitly given salt is ignored.

    See this for more information about how the hash is made up