Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
PHP BCRYPT cost calculator
<?php
/**
* Password BCRYPT Hash Cost Calculator
*
* Just upload this script to your server and run it, either through CLI or by calling it in your browser.
*
* You should choose a cost that will take at least 100ms
*/
// Upper time limit to check
$upperTimeLimit = 1000;
$password = 'this_is_just_a_long_string_to_test_on_U8WNZqmz8ZVBNiNTQR8r';
if (php_sapi_name() !== 'cli' ) echo "<pre>";
echo "\nPassword BCRYPT Hash Cost Calculator\n\n";
echo "We're going to run until the time to generate the hash takes longer than {$upperTimeLimit}ms\n";
$cost = 3;
$first_cost_above_100 = null;
$first_cost_above_500 = null;
do {
$cost++;
echo "\nTesting cost value of $cost: ";
$start = microtime(true);
password_hash($password, PASSWORD_BCRYPT, array('cost' => $cost));
$time = round((microtime(true) - $start) * 1000);
echo "... took {$time}ms";
if ($first_cost_above_100 === null && $time > 100) {
$first_cost_above_100 = $cost;
} else if ($first_cost_above_500 === null && $time > 500) {
$first_cost_above_500 = $cost;
}
} while ($time < $upperTimeLimit);
echo "\n\n\nYou should use a cost between $first_cost_above_100 and $first_cost_above_500";
if (php_sapi_name() !== 'cli' ) echo "</pre>";
@Indigo744

This comment has been minimized.

Copy link
Owner Author

commented Mar 20, 2018

Here is an example output:

Password BCRYPT Hash Cost Calculator

We're going to run until the time to generate the hash takes longer than 1000ms

Testing cost value of 4: ... took 1ms
Testing cost value of 5: ... took 2ms
Testing cost value of 6: ... took 4ms
Testing cost value of 7: ... took 8ms
Testing cost value of 8: ... took 16ms
Testing cost value of 9: ... took 31ms
Testing cost value of 10: ... took 61ms
Testing cost value of 11: ... took 122ms
Testing cost value of 12: ... took 244ms
Testing cost value of 13: ... took 489ms
Testing cost value of 14: ... took 976ms
Testing cost value of 15: ... took 1967ms


You should use a cost between 11 and 14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.