I took information from a series of posts and some prior knowledge to implement the following hashing algorithm.
However, there is a lot of talk about what implementations are secure and not secure. How does my method measure up? Is it secure? Are there more secure methods in PHP for hashing tokens and matching with tokens later on?
public static function sha512($token,$cost = 50000,$salt = null) {
$salt = ($salt == null) ? (generateToken(32)) : ($salt);
$salt = '$6$rounds=' . $cost . '$' . $salt . ' $';
return crypt($token, $salt);
}
public static function sha512Equals($token,$hash) {
return (crypt($token,$hash) == $hash);
}
public static function generateToken($length,$characterPool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
$token = '';
$max = mb_strlen($characterPool);
for ($i = 0;$i < $length;$i++){
$token .= $characterPool[cryptorand(0,$max)];
}
return $token;
}
public static function cryptorand($min, $max) {
$range = $max - $min;
if ($range < 0)
return $min;
$log = log($range, 2);
$bytes = (int) ($log / 8) + 1; // length in bytes
$bits = (int) $log + 1; // length in bits
$filter = (int) (1 << $bits) - 1; // set all lower bits to 1
do {
$rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes)));
$rnd = $rnd & $filter; // discard irrelevant bits
} while ($rnd >= $range);
return $min + $rnd;
}
bcrypt
functions? Also, you should read this: security.stackexchange.com/questions/211/…. It's focused on storing passwords, but you can extract good information. \$\endgroup\$bcrypt
orPBKDF2
. I mean, sure, play around with cryptography and write some code to learn more about it, but never use it in production with real people's data. Period. \$\endgroup\$