Laravel 5: using bcrypt on same string gives different values

user6737580 picture user6737580 · Aug 29, 2016 · Viewed 14.6k times · Source

I am using Laravel's bcrypt function for hashing passwords. When I do,

bcrypt('secret')

I get

=> "$2y$10$mnPgYt2xm9pxb/c2I.SH.uuhgrOj4WajDQTJYssUbTjmPOcgQybcu"

But if I run it again, I get

=> "$2y$10$J8h.Xmf6muivJ4bDweUlcu/BaNzI2wlBiAcop30PbPoKa0kDaf9xi"

and so on...

So, won't the password matching process fail if I get different values every time?

Answer

linuxartisan picture linuxartisan · Aug 29, 2016

This is how bcrypt is supposed to work. See wikipedia.

Bcrypt generates a random 128-bit salt during hashing. This salt becomes part of the hash, hence we always get a different hash value for the same input string. The random salt is actually used to deter brute-force attacks.

The password matching process won't fail due to different values of hashes. Try the following in tinker

$hash1 = bcrypt('secret')
$hash2 = bcrypt('secret')

Hash::check('secret', $hash1)
Hash::check('secret', $hash2)

You should get true in both the cases of Hash::check.

So even if the hash values are different, the password matching won't fail.