Add odd number of character support to random_string()

This commit is contained in:
Hypolite Petovan 2017-11-26 07:57:29 -05:00
parent d38c040d50
commit d5c38b9fc9

View file

@ -41,26 +41,19 @@ function replace_macros($s, $r) {
return $output; return $output;
} }
// PHP < 7 polyfill
if (!is_callable('intdiv')) {
function intdiv($a, $b) {
return ($a - $a % $b) / $b;
}
}
/** /**
* @brief Generates a pseudo-random string of hexadecimal characters * @brief Generates a pseudo-random string of hexadecimal characters
* *
* Only supports pair numbers of output characters.
*
* @param int $size * @param int $size
* @return string * @return string
*/ */
function random_string($size = 64) function random_string($size = 64)
{ {
$bytes = random_bytes(intdiv((int) $size, 2)); $byte_size = ceil($size / 2);
$return = bin2hex($bytes); $bytes = random_bytes($byte_size);
$return = substr(bin2hex($bytes), 0, $size);
return $return; return $return;
} }