Commit 9af5ac62 authored by Côme Chilliet's avatar Côme Chilliet
Browse files

: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
Showing with 7 additions and 4 deletions
+7 -4
...@@ -2471,22 +2471,25 @@ if (!function_exists('random_int')) { ...@@ -2471,22 +2471,25 @@ if (!function_exists('random_int')) {
throw new Exception('Invalid range passed to random_int'); throw new Exception('Invalid range passed to random_int');
} }
$log = log($range, 2); $log = log($range, 2);
// length in bytes // length in bytes
$nbBytes = (int) ($log / 8) + 1; $nbBytes = (int) ($log / 8) + 1;
// length in bits // length in bits
$nbBits = (int) $log + 1; $nbBits = (int) $log + 1;
// set all lower bits to 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 { do {
$randomBytes = openssl_random_pseudo_bytes($nbBytes, $strong); $randomBytes = openssl_random_pseudo_bytes($nbBytes, $strong);
if (!$strong || ($randomBytes === FALSE)) { if (!$strong || ($randomBytes === FALSE)) {
throw new Exception('Failed to get random bytes'); throw new Exception('Failed to get random bytes');
} }
$rnd = unpack('L', $randomBytes)[1]; $rnd = hexdec(bin2hex($randomBytes));
// discard irrelevant bits // discard irrelevant bits
$rnd = $rnd & $filter; $rnd = $rnd & $filter;
} while ($rnd >= $range); } while ($rnd > $range);
return $min + $rnd; return $min + $rnd;
} }
} }
......
  • bmortier @bmortier

    mentioned in commit 42c7fb5c

    By Côme Chilliet on 2018-07-03T11:18:06 (imported from GitLab)

    ·

    mentioned in commit 42c7fb5c

    By Côme Chilliet on 2018-07-03T11:18:06 (imported from GitLab)

    Toggle commit list
  • bmortier @bmortier

    mentioned in merge request !326

    By Côme Chilliet on 2018-07-03T11:18:45 (imported from GitLab)

    ·

    mentioned in merge request !326

    By Côme Chilliet on 2018-07-03T11:18:45 (imported from GitLab)

    Toggle commit list
  • bmortier @bmortier

    mentioned in commit 5c17cfc5

    By Côme Chilliet on 2018-07-03T11:55:46 (imported from GitLab)

    ·

    mentioned in commit 5c17cfc5

    By Côme Chilliet on 2018-07-03T11:55:46 (imported from GitLab)

    Toggle commit list
  • bmortier @bmortier

    mentioned in merge request !327

    By Côme Chilliet on 2018-07-03T11:55:59 (imported from GitLab)

    ·

    mentioned in merge request !327

    By Côme Chilliet on 2018-07-03T11:55:59 (imported from GitLab)

    Toggle commit list
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment