From: konrad Date: Sat, 23 Oct 2010 21:01:27 +0000 (+0000) Subject: better random number generator X-Git-Url: http://git.silmor.de/gitweb/?a=commitdiff_plain;h=115508d005430ab8cb7d66fcbb801b1e0ed7573b;p=web%2Fkonrad%2Fsmoke.git better random number generator git-svn-id: https://silmor.de/svn/softmagic/smoke/trunk@609 6e3c4bff-ac9f-4ac1-96c5-d2ea494d3e33 --- diff --git a/www/inc/classes/random.php b/www/inc/classes/random.php index 62ec275..32b9eac 100644 --- a/www/inc/classes/random.php +++ b/www/inc/classes/random.php @@ -23,36 +23,44 @@ function randseedfile($fn,$sz) } //get current random seed -$RANDSEED="".microtime(); +$RANDSEED=""; $RANDCTR=0; -if($db->canUseDb())$RANDSEED.=$db->getConfig("randseed"); -if(file_exists("/dev/urandom"))randseedfile("/dev/urandom",64); -if(file_exists("/dev/random"))randseedfile("/dev/random",16); -if(isset($_SERVER["UNIQUE_ID"]))$RANDSEED.=$_SERVER["UNIQUE_ID"]; -/**add some seed into the random function*/ -function randseed($rand) +//initialize random seed +function randseedinit() { - global $RANDSEED; - $RANDSEED.=$rand; + global $RANDSEED,$_SERVER; + //very basic initialization + $RANDSEED.=microtime().uniqid("",true); + //attempt to use OpenSSL + if (function_exists('openssl_random_pseudo_bytes')) { + $RANDSEED .= openssl_random_pseudo_bytes(64, $strong); + // if it was strong, be happy and leave + if($strong === true) { + return; + } + } + //attempt to use /dev/(u)random + if(file_exists("/dev/urandom"))randseedfile("/dev/urandom",64); + else if(file_exists("/dev/random"))randseedfile("/dev/random",20); + //last resort: get what we got from apache + if(isset($_SERVER["UNIQUE_ID"]))$RANDSEED.=$_SERVER["UNIQUE_ID"]; } -/**return $bits bits of random data*/ +/**return $bits bits of random data as hex string*/ function getRandom($bits) { //number of digits... $bits/=4; //init - global $RANDSEED,$db,$RANDCTR; - $ret="";$ctr=0; + global $RANDSEED,$RANDCTR; + if($RANDSEED=="")randseedinit(); + $ret=""; //get string while(strlen($ret)<$bits){ $ret.=sha1($RANDSEED.microtime().$RANDCTR); $RANDCTR++; } - //rewrite seed to DB - $RANDSEED=sha1($RANDSEED.microtime().$ret.$RANDCTR);$RANDCTR=0; - $db->setConfig("randseed",$RANDSEED); //return return substr($ret,0,$bits); }