From 9af5ac62dcc273853d9d59f9df3072753c23074e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=B4me=20Chilliet?= <come@opensides.be> Date: Tue, 3 Jul 2018 13:01:47 +0200 Subject: [PATCH] :ambulance: fix(core) Give using unpack for bytes conversion Now bin2hex and hexdec are used instead, so hexadecimal is used as an intermediate for the conversion. Also, fix a bug that max was never returned. Also fixed filter which was turning result negative in some cases. issue #5843 --- include/functions.inc | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/include/functions.inc b/include/functions.inc index f99669831..ee822ff04 100644 --- a/include/functions.inc +++ b/include/functions.inc @@ -2471,22 +2471,25 @@ if (!function_exists('random_int')) { throw new Exception('Invalid range passed to random_int'); } - $log = log($range, 2); + $log = log($range, 2); // length in bytes $nbBytes = (int) ($log / 8) + 1; // length in bits $nbBits = (int) $log + 1; // set all lower bits to 1 - $filter = (int) (1 << $nbBits) - 1; + $filter = pow(2, $nbBits) - 1; + if ($filter >= PHP_INT_MAX) { + $filter = PHP_INT_MAX; + } do { $randomBytes = openssl_random_pseudo_bytes($nbBytes, $strong); if (!$strong || ($randomBytes === FALSE)) { throw new Exception('Failed to get random bytes'); } - $rnd = unpack('L', $randomBytes)[1]; + $rnd = hexdec(bin2hex($randomBytes)); // discard irrelevant bits $rnd = $rnd & $filter; - } while ($rnd >= $range); + } while ($rnd > $range); return $min + $rnd; } } -- GitLab