ircmaxell / password_compat

Compatibility with the password_* functions that ship with PHP 5.5
MIT License
2.15k stars 421 forks source link

Password that is being returned varies? #39

Closed ghost closed 10 years ago

ghost commented 10 years ago

I've been using this library for a while, but I encountered issues with my login system today. After extensive debugging including at least four code refactors, I've finally narrowed the issue down to (unfortunately) this library. I downloaded this copy on the 26th of November, and the basic issue is that the hash being returned for a predefined password varies between page loads. For instance, I am currently hashing a simple string, "admin". A sample hash is "$2y$12$3M46vmkpRtgvanC.ViCBJuXnIieGTqWHG7csDdsOKbJHDFlNCQ7kW", followed by "$2y$12$QsgXA6f1itohqd5YA0XhI.18EjF5B45RKwRFSD4Eic3M9vf3FtpDO" on the next load. This is the code I am using:

password_hash($pass, PASSWORD_BCRYPT, array("cost" => 12));

For reference, when I use a plain md5() hash, it returns a constant, expected value of "21232f297a57a5a743894a0e4a801fc3".

I am using PHP 5.4.7 on a Windows 7 installation (WAMPServer).

bpearson commented 10 years ago

Unless I am missing something, isn't that what it should do? Hashing a static password would add a random salt thus giving a different hash result on each iteration.

Just curious, but if you are logging a person in, are you using the password_verify() function? The function password_hash() should only be used by the developer to store a new hash (generally speaking).

phindmarsh commented 10 years ago

This is by design. The same password will not return the same hash. In order to verify whether the password supplied by the user you need to use the password_verify($password, $hash) function, so in your case:

$matches = password_verify('admin', '$2y$12$3M46vmkpRtgvanC.ViCBJuXnIieGTqWHG7csDdsOKbJHDFlNCQ7kW');

This is because for each time you generate a new hash using password_hash a new salt is generated (the bit between the third dollar sign ($) and the dot (.) in the outputted hash. In the above example the salt is 3M46vmkpRtgvanC with a work factor of 12 and using the 2y crypt algorithm.

ghost commented 10 years ago

I am using the password_verify function, I'm not hashing it again. My login system has been plagued by a bug that is not letting me login and I thought that this was the reason. Thanks anyway for explaining it to me. :)