Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Generate pseudo random bits using the best available method.
- *
- * @param int $bits amount of random bits to generate.
- * @param bool $secure Use a cryptographically secure method of getting these random bits.
- * @param int $output_type The output type for the generated bits.
- * @return string A (pseudo) random string.
- *
- * @copyright: public domain
- * @author Beanow
- * @link http://tuxion.nl
- * @note Don't try to improve this, you will likely just ruin it
- * @note I did it anyways. Regards ~Beanow
- */
- private function _random_bits($bits, $secure=true, $output_type=self::OUTPUT_HEX)
- {
- //Obviously *NIX is for pro's and so we should use it's generator if available.
- //Ok the real reason is that it gives high entropy by gathering noise on an OS level.
- //So using that makes this function a lot faster and more safe.
- if (@is_readable('/dev/urandom')){
- $f=fopen('/dev/urandom', 'rb');
- $str=fread($f, $bits/8);
- fclose($f);
- }
- //If we don't have it we're going to make the best out of getting microtime() bits of randomness.
- else
- {
- //Generate more entropy starting state, to give it that extra bit of spunk. :D
- $state = uniqid('', true);
- $str = '';
- //Increment with 20, because microtime() generates 6 decimals which is almost 20 bits.
- //The fraction of the last bit that isn't available from microtime() comes from mt_rand().
- //However if $secure is set to false we don't care and take the size of the hash output instead.
- //This will make the algorithm faster but will contain much less (~60%) entropy.
- //Note that the state hash and string appending hash are different and should be!
- //It makes it impossible for the state to leak into the output stream.
- for ($i = 0; $i < $bits; $i += ($secure === true ? 20 : 52)){
- $state = $this->hash(microtime().$state.mt_rand(), self::$HASH_PREFERENCES['128'][0]);
- $str .= $this->hash(microtime().$state, self::$HASH_PREFERENCES['128'][0], self::OUTPUT_BINARY);
- }
- }
- //Do a final hash to compress all entropy to an optimal inclusive hash.
- return $this->hash($str, $this->pref_hash_algo($bits, true), $output_type);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement