From ffd94de39821a804365d66f66a7af0bfb03a0e5c Mon Sep 17 00:00:00 2001 From: Russell Smith Date: Tue, 16 Aug 2016 12:12:11 +1000 Subject: [PATCH] MDL-55272 lib: Allow random_bytes() to return large values. PHP has a recursion limit and random_bytes on PHP5.6 without openssl will error if sent a large value. Using a loop has lower overhead than recursion as well. --- lib/moodlelib.php | 12 ++++++------ lib/tests/moodlelib_test.php | 3 +++ 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/lib/moodlelib.php b/lib/moodlelib.php index 0e312184125..b8f141be875 100644 --- a/lib/moodlelib.php +++ b/lib/moodlelib.php @@ -7637,12 +7637,12 @@ function random_bytes_emulate($length) { } // Bad luck, there is no reliable random generator, let's just hash some unique stuff that is hard to guess. - $hash = sha1(serialize($CFG) . serialize($_SERVER) . microtime(true) . uniqid('', true), true); - // NOTE: the last param in sha1() is true, this means we are getting 20 bytes, not 40 chars as usual. - if ($length <= 20) { - return substr($hash, 0, $length); - } - return $hash . random_bytes_emulate($length - 20); + $staticdata = serialize($CFG) . serialize($_SERVER); + $hash = ''; + do { + $hash .= sha1($staticdata . microtime(true) . uniqid('', true), true); + } while (strlen($hash) < $length); + return substr($hash, 0, $length); } /** diff --git a/lib/tests/moodlelib_test.php b/lib/tests/moodlelib_test.php index f74df9382db..8e94aec6e95 100644 --- a/lib/tests/moodlelib_test.php +++ b/lib/tests/moodlelib_test.php @@ -2930,6 +2930,9 @@ class core_moodlelib_testcase extends advanced_testcase { $result = random_bytes_emulate(666); $this->assertSame(666, strlen($result)); + $result = random_bytes_emulate(40); + $this->assertSame(40, strlen($result)); + $this->assertDebuggingNotCalled(); $result = random_bytes_emulate(0);