Skip to content

Instantly share code, notes, and snippets.

@s3b4stian
Created February 21, 2017 21:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save s3b4stian/7776900cd746398a46c9a4e38dbf2040 to your computer and use it in GitHub Desktop.
Save s3b4stian/7776900cd746398a46c9a4e38dbf2040 to your computer and use it in GitHub Desktop.
Get appropriate cost for password hashing
/**
* Get appropriate cost
*
* This code will benchmark your server to determine how high of a cost you can
* afford. You want to set the highest cost that you can without slowing down
* you server too much.
*
* @param int $time_limit Time limit in milliseconds
* @param int $algo Algoritm, default PASSWORD_DEFAULT
* @return int
*/
function password_get_appropriate_cost(int $time_limit, int $algo = PASSWORD_DEFAULT) : int
{
//set start cost
$cost = 3;
do {
//increase cost
$cost++;
//check if cost is out of range for bcrypt
if ($algo === 1 && ($cost < 4 || $cost > 31)) {
break;
}
//start time
$start = microtime(true);
//generate password
password_hash("test", $algo, ["cost" => $cost]);
//stop time
$end = microtime(true);
} while (($end - $start) < ($time_limit / 100));
return $cost;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment