1
0
mirror of https://github.com/phpbb/phpbb.git synced 2025-05-17 04:51:35 +02:00

Merge pull request #5259 from rubencm/ticket/15695

[ticket/15695] Fix gen_rand_string returning less characters than expected
This commit is contained in:
Marc Alexander 2018-06-19 13:32:10 +02:00
commit 754945e6ff

View File

@ -66,27 +66,29 @@ function set_var(&$result, $var, $type, $multibyte = false)
/** /**
* Generates an alphanumeric random string of given length * Generates an alphanumeric random string of given length
* *
* @param int $num_chars Length of random string, defaults to 8 * @param int $num_chars Length of random string, defaults to 8.
* This number should be less or equal than 64.
* *
* @return string * @return string
*/ */
function gen_rand_string($num_chars = 8) function gen_rand_string($num_chars = 8)
{ {
// [a, z] + [0, 9] = 36 // [a, z] + [0, 9] = 36
return substr(strtoupper(base_convert(bin2hex(random_bytes($num_chars)), 16, 36)), 0, $num_chars); return substr(strtoupper(base_convert(bin2hex(random_bytes($num_chars + 1)), 16, 36)), 0, $num_chars);
} }
/** /**
* Generates a user-friendly alphanumeric random string of given length * Generates a user-friendly alphanumeric random string of given length
* We remove 0 and O so users cannot confuse those in passwords etc. * We remove 0 and O so users cannot confuse those in passwords etc.
* *
* @param int $num_chars Length of random string, defaults to 8 * @param int $num_chars Length of random string, defaults to 8.
* This number should be less or equal than 64.
* *
* @return string * @return string
*/ */
function gen_rand_string_friendly($num_chars = 8) function gen_rand_string_friendly($num_chars = 8)
{ {
$rand_str = bin2hex(random_bytes($num_chars)); $rand_str = bin2hex(random_bytes($num_chars + 1));
// Remove Z and Y from the base_convert(), replace 0 with Z and O with Y // Remove Z and Y from the base_convert(), replace 0 with Z and O with Y
// [a, z] + [0, 9] - {z, y} = [a, z] + [0, 9] - {0, o} = 34 // [a, z] + [0, 9] - {z, y} = [a, z] + [0, 9] - {0, o} = 34