diff options
author | Simon Rettberg | 2017-01-19 16:03:06 +0100 |
---|---|---|
committer | Simon Rettberg | 2017-01-19 16:03:06 +0100 |
commit | 886e13e1af47ba6488ba3c5146d96e48e08403ad (patch) | |
tree | dd0da56ccf6f2e5ae9e4e6b1e5709b911d255164 /inc/util.inc.php | |
parent | [statistics_reporting] i18n: Move tags used in code to separate file, delete ... (diff) | |
download | slx-admin-886e13e1af47ba6488ba3c5146d96e48e08403ad.tar.gz slx-admin-886e13e1af47ba6488ba3c5146d96e48e08403ad.tar.xz slx-admin-886e13e1af47ba6488ba3c5146d96e48e08403ad.zip |
[statistics_reporting] Overhaul remote reporting structure; default to off
Diffstat (limited to 'inc/util.inc.php')
-rw-r--r-- | inc/util.inc.php | 52 |
1 files changed, 52 insertions, 0 deletions
diff --git a/inc/util.inc.php b/inc/util.inc.php index 671028ed..d454d18d 100644 --- a/inc/util.inc.php +++ b/inc/util.inc.php @@ -365,4 +365,56 @@ SADFACE; exit(0); } + /** + * Return a binary string of given length, containing + * random bytes. If $secure is given, only methods of + * obtaining cryptographically strong random bytes will + * be used, otherwise, weaker methods might be used. + * + * @param int $length number of bytes to return + * @param bool $secure true = only use strong random sources + * @return string|bool string of requested length, false on error + */ + public static function randomBytes($length, $secure) + { + if (function_exists('random_bytes')) { + return random_bytes($length); + } + if ($secure) { + if (function_exists('openssl_random_pseudo_bytes')) { + $bytes = openssl_random_pseudo_bytes($length, $ok); + if ($bytes !== false && $ok) { + return $bytes; + } + } + $file = '/dev/random'; + } else { + $file = '/dev/urandom'; + } + $fh = @fopen($file, 'r'); + if ($fh !== false) { + $bytes = fread($fh, $length); + while ($bytes !== false && strlen($bytes) < $length) { + $new = fread($fh, $length - strlen($bytes)); + if ($new === false) { + $bytes = false; + break; + } + $bytes .= $new; + } + fclose($fh); + if ($bytes !== false) { + return $bytes; + } + } + if ($secure) { + return false; + } + $bytes = ''; + while ($length > 0) { + $bytes .= chr(mt_rand(0, 255)); + } + return $bytes; + } + } |