Advertisement
Guest User

First version

a guest
Jan 30th, 2012
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.18 KB | None | 0 0
  1. /**
  2.  * Generate pseudo random bits using the best available method.
  3.  *
  4.  * @param int $bits amount of random bits to generate.
  5.  * @param bool $secure Use a cryptographically secure method of getting these random bits.
  6.  * @param int $output_type The output type for the generated bits.
  7.  * @return string A (pseudo) random string.
  8.  *
  9.  * @copyright: public domain
  10.  * @author Beanow
  11.  * @link http://tuxion.nl
  12.  * @note Don't try to improve this, you will likely just ruin it
  13.  * @note I did it anyways. Regards ~Beanow
  14.  */
  15. private function _random_bits($bits, $secure=true, $output_type=self::OUTPUT_HEX)
  16. {
  17.  
  18.   //Obviously *NIX is for pro's and so we should use it's generator if available.
  19.   //Ok the real reason is that it gives high entropy by gathering noise on an OS level.
  20.   //So using that makes this function a lot faster and more safe.
  21.   if (@is_readable('/dev/urandom')){
  22.     $f=fopen('/dev/urandom', 'rb');
  23.     $str=fread($f, $bits/8);
  24.     fclose($f);
  25.   }
  26.  
  27.   //If we don't have it we're going to make the best out of getting microtime() bits of randomness.
  28.   else
  29.   {
  30.      
  31.     //Generate more entropy starting state, to give it that extra bit of spunk. :D
  32.     $state = uniqid('', true);
  33.     $str = '';
  34.    
  35.     //Increment with 20, because microtime() generates 6 decimals which is almost 20 bits.
  36.     //The fraction of the last bit that isn't available from microtime() comes from mt_rand().
  37.     //However if $secure is set to false we don't care and take the size of the hash output instead.
  38.     //This will make the algorithm faster but will contain much less (~60%) entropy.
  39.     //Note that the state hash and string appending hash are different and should be!
  40.     //It makes it impossible for the state to leak into the output stream.
  41.     for ($i = 0; $i < $bits; $i += ($secure === true ? 20 : 52)){
  42.       $state = $this->hash(microtime().$state.mt_rand(), self::$HASH_PREFERENCES['128'][0]);
  43.       $str .= $this->hash(microtime().$state, self::$HASH_PREFERENCES['128'][0], self::OUTPUT_BINARY);
  44.     }
  45.    
  46.   }
  47.  
  48.   //Do a final hash to compress all entropy to an optimal inclusive hash.
  49.   return $this->hash($str, $this->pref_hash_algo($bits, true), $output_type);
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement