From 6989e51c23c7ab81bc7b7c5b6dd0fb9f90fe2c7a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andreas=20=C3=85kre=20Solberg?= <andreas.solberg@uninett.no> Date: Mon, 1 Sep 2008 12:48:34 +0000 Subject: [PATCH] Added a fallback solution if having troubles with dev/urandom. Discovered a case where RHEL4 returned one more byte than requested... git-svn-id: https://simplesamlphp.googlecode.com/svn/trunk@851 44740490-163a-0410-bde0-09ae8108e29a --- lib/SimpleSAML/Utilities.php | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/lib/SimpleSAML/Utilities.php b/lib/SimpleSAML/Utilities.php index b8fb39cf9..5a5ce5b01 100644 --- a/lib/SimpleSAML/Utilities.php +++ b/lib/SimpleSAML/Utilities.php @@ -987,6 +987,16 @@ class SimpleSAML_Utilities { return $userid; } + public static function generateRandomBytesMTrand($length) { + + /* Use mt_rand to generate $length random bytes. */ + $data = ''; + for($i = 0; $i < $length; $i++) { + $data .= chr(mt_rand(0, 255)); + } + + } + /** * This function generates a binary string containing random bytes. @@ -996,7 +1006,7 @@ class SimpleSAML_Utilities { * @param $length The number of random bytes to return. * @return A string of lenght $length with random bytes. */ - public static function generateRandomBytes($length) { + public static function generateRandomBytes($length, $fallback = TRUE) { static $fp = NULL; assert('is_int($length)'); @@ -1011,14 +1021,16 @@ class SimpleSAML_Utilities { throw new Exception('Error reading random data.'); } if(strlen($data) != $length) { - throw new Exception('Did not get requested number of bytes from random source.'); + SimpleSAML_Logger::warning('Did not get requested number of bytes from random source. Requested (' . $length . ') got (' . strlen($data) . ')'); + if ($fallback) { + $data = self::generateRandomBytesMTrand($length); + } else { + throw new Exception('Did not get requested number of bytes from random source. Requested (' . $length . ') got (' . strlen($data) . ')'); + } } } else { /* Use mt_rand to generate $length random bytes. */ - $data = ''; - for($i = 0; $i < $length; $i++) { - $data .= chr(mt_rand(0, 255)); - } + $data = self::generateRandomBytesMTrand($length); } return $data; -- GitLab