Created
February 21, 2017 21:37
-
-
Save s3b4stian/7776900cd746398a46c9a4e38dbf2040 to your computer and use it in GitHub Desktop.
Get appropriate cost for password hashing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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