3 * The Microtime Random Number Source
5 * This uses the current micro-second (looped several times) for a **very** weak
6 * random number source. This is only useful when combined with several other
11 * @category PHPCryptLib
14 * @author Anthony Ferrara <ircmaxell@ircmaxell.com>
15 * @copyright 2011 The Authors
16 * @license http://www.opensource.org/licenses/mit-license.html MIT License
17 * @version Build @@version@@
20 namespace CryptLib\Random\Source
;
22 use CryptLib\Core\Strength
;
25 * The Microtime Random Number Source
27 * This uses the current micro-second (looped several times) for a **very** weak
28 * random number source. This is only useful when combined with several other
31 * @category PHPCryptLib
34 * @author Anthony Ferrara <ircmaxell@ircmaxell.com>
37 class MicroTime
implements \CryptLib\Random\Source
{
39 private $state = null;
42 * Return an instance of Strength indicating the strength of the source
44 * @return Strength An instance of one of the strength classes
46 public static function getStrength() {
47 return new Strength(Strength
::VERYLOW
);
50 public function __construct() {
52 if (function_exists('posix_times')) {
53 $state .= serialize(posix_times());
55 $state .= getmypid() . memory_get_usage();
56 $state .= serialize($_ENV);
57 $this->state
= hash('sha512', $state, true);
61 * Generate a random string of the specified size
63 * @param int $size The size of the requested random string
65 * @return string A string of the requested size
67 public function generate($size) {
69 $seed = microtime() . memory_get_usage();
70 $this->state
= hash('sha512', $this->state
. $seed, true);
72 * Make the generated randomness a bit better by forcing a GC run which
73 * should complete in a indeterminate amount of time, hence improving
74 * the strength of the randomness a bit. It's still not crypto-safe,
75 * but at least it's more difficult to predict.
78 for ($i = 0; $i < $size; $i +
= 8) {
79 $seed = $this->state
. microtime() . pack('N', $i);
80 $this->state
= hash('sha512', $seed, true);
82 * We only use the first 8 bytes here to prevent exposing the state
83 * in its entirety, which could potentially expose other random
84 * generations in the future (in the same process)...
86 $result .= substr($this->state
, 0, 8);
88 return substr($result, 0, $size);