Skip to content
Browse files

Fallback to /dev/random if openssl_random_pseudo_bytes not available

  • Loading branch information...
1 parent 99cd922 commit d6c4b83f13976b19f471ce3a02c5b872c2f79bdc @LukasReschke LukasReschke committed Oct 14, 2012
Showing with 14 additions and 6 deletions.
  1. +14 −6 lib/util.php
View
20 lib/util.php
@@ -556,22 +556,30 @@ public static function ishtaccessworking() {
}
/*
- * @brief Generates random bytes with "openssl_random_pseudo_bytes" with a fallback for systems without openssl
- * Inspired by gorgo on php.net
- * @param Int with the length of the random
- * @return String with the random bytes
+ * @brief Generates a cryptographical secure pseudorandom string
+ * @param Int with the length of the random string
+ * @return String
*/
public static function generate_random_bytes($length = 30) {
+
+ // Try to use openssl_random_pseudo_bytes
if(function_exists('openssl_random_pseudo_bytes')) {
$pseudo_byte = bin2hex(openssl_random_pseudo_bytes($length, $strong));
if($strong == TRUE) {
return substr($pseudo_byte, 0, $length); // Truncate it to match the length
}
}
- // fallback to mt_rand()
+ // Try to use /dev/random
+ $fp = @file_get_contents('/dev/random', false, null, 0, $length);
+ if ($fp !== FALSE) {
+ $string = substr(bin2hex($fp), 0, $length);
+ return $string;
+ }
+
+ // Fallback to mt_rand()
$characters = '0123456789';
- $characters .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
+ $characters .= 'abcdefghijklmnopqrstuvwxyz';
$charactersLength = strlen($characters)-1;
$pseudo_byte = "";

0 comments on commit d6c4b83

Please sign in to comment.
Something went wrong with that request. Please try again.