Laravel 5: Hashing Strings With bcrypt

April 14, 2018 —John Koster

The bcrypt function will return a hashed representation of the given $value. The bcrypt function also accepts an array of $options which can be used to affect how the hash is computed. Each invocation of the bcrypt function should produce a different result, even if the input remains the same.

#Signature

The signature for the bcrypt function is:

1function bcrypt(
2 $value,
3 $options = []
4);

#Example Use

The following example demonstrates how to call the bcrypt function:

1for ($i = 0; $i < 10; $i++)
2{
3 // echo the hash and an HTML line break
4 echo bcrypt('test'),'<br>';
5}

The above example would output something similar to this:

1$2y$10$6b8WZt.Ugwnjjb3JZQH51ecaG.VSjOOO2xCZ3t4s/MGGHU112hhD2
2$2y$10$o/uJXcnrNDQraGgk1.VG9.LwssnANCyOEO8tCuiL5RlO33CpGo.Lq
3$2y$10$7qWDkO43obCCN4hpNDt2Hut2xbg8xmKQHzZF/m4EdsGUHApXcKLyi
4$2y$10$e4srCMoCOaIl9qd2wuk.8e2pBGTxaAu/bDi2CrNlRcNyXxvtYePIy
5$2y$10$1MhsM.KaYpwoODuoBi7wmO6jUrMJ0xGaigL6/JMKAgb48CgyFz8tK
6$2y$10$wTdq3XAG7/UKT0aO4u9lO.ZRcDiaF5p4fXMViticodID9oC/CTsJO
7$2y$10$yHwchZ9HCKZjfnqqulQ7eu61noEwIVZBXKwSZ8.rvYyk9p0SXFNKG
8$2y$10$5XvPyJE9EQ6DpOdYzM.NYeR4eDjAzntn2ogytDh1tNU4ebWrHaYvS
9$2y$10$V1yb7D7rqqUL7BZkR2c3HOjYHvVB/lRg5cvrL/Hl/KYzrKrTV/tvC
10$2y$10$6DAP/IjDTOH3iezOzx/CyuH37ZEDtc6.ADkDEfJUUn/msgUGe5A4S

#Available Options

The following table lists all of the options that are available to use in with the bcrypt function.

bcrypt Options:

Option Description
rounds Determines how many iterations the bcrypt function will internally use.

#rounds

The rounds option is used to control how many iterations the underlying Blowfish implementation will use when generating the final hash. The rounds value can be any positive integer between 4 and 31 (including both 4 and 31). If an integer outside the stated range is supplied an ErrorException will be thrown. The rounds option is synonymous with the cost option when using PHP's password_hash or crypt functions. Increasing the rounds will also increase the time required to compute the hash. The default value for this option is 10.

Laravel's bcrypt APIs expose the algorithmic cost option as rounds. Internally, Laravel will remap the value of rounds to the cost option before invoking the password_hash function.

1// Compute a hash with a 'cost' of 4
2bcrypt('test', ['rounds' => 4]);
3 
4// Compute a hash with a 'cost' of 5
5bcrypt('test', ['rounds' => 4]);
6 
7// These will throw an `ErrorException`
8bcrypt('test', ['rounds' => 3]);
9bcrypt('test', ['founds' => 32]);

The number of iterations that will be used can be determined with the following equation:

1iterations = 2^rounds

Calling bcrypt with the rounds option set to 10 will use 2^10 or 1024 iterations.

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.