Completed
Push — master ( 4d4232...ffcfa4 )
by Anthony
14:02 queued 11:53
created

MicroTime::getStrength()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 3
rs 10
nc 1
cc 1
eloc 2
nop 0
1
<?php
2
/**
3
 * The Microtime Random Number Source
4
 *
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
7
 * stronger sources
8
 *
9
 * PHP version 5.3
10
 *
11
 * @category   PHPCryptLib
12
 * @package    Random
13
 * @subpackage Source
14
 * @author     Anthony Ferrara <[email protected]>
15
 * @copyright  2011 The Authors
16
 * @license    http://www.opensource.org/licenses/mit-license.html  MIT License
17
 * @version    Build @@version@@
18
 */
19
20
namespace RandomLib\Source;
21
22
use SecurityLib\Strength;
23
use SecurityLib\Util;
24
25
/**
26
 * The Microtime Random Number Source
27
 *
28
 * This uses the current micro-second (looped several times) for a **very** weak
29
 * random number source.  This is only useful when combined with several other
30
 * stronger sources
31
 *
32
 * @category   PHPCryptLib
33
 * @package    Random
34
 * @subpackage Source
35
 * @author     Anthony Ferrara <[email protected]>
36
 * @codeCoverageIgnore
37
 */
38
final class MicroTime extends \RandomLib\AbstractSource {
39
40
    /**
41
     * A static counter to ensure unique hashes and prevent state collisions
42
     * @var int A counter
43
     */
44
    private static $counter = null;
45
46
    /**
47
     * The current state of the random number generator.
48
     * @var string The state of the PRNG
49
     */
50
    private static $state = '';
51
52
    public function __construct() {
0 ignored issues
show
Coding Style introduced by
__construct uses the super-global variable $_ENV which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
Coding Style introduced by
__construct uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
53
        $state = self::$state;
54
        if (function_exists('posix_times')) {
55
            $state .= serialize(posix_times());
56
        }
57
        if (!defined('HHVM_VERSION') && function_exists('zend_thread_id')) {
58
            $state .= zend_thread_id();
59
        }
60
        if (function_exists('hphp_get_thread_id')) {
61
            $state .= hphp_get_thread_id();
62
        }
63
        $state      .= getmypid() . memory_get_usage();
64
        $state      .= serialize($_ENV);
65
        $state      .= serialize($_SERVER);
66
        $state      .= count(debug_backtrace(false));
67
        self::$state = hash('sha512', $state, true);
68
        if (is_null(self::$counter)) {
69
            list( , self::$counter) = unpack("i", Util::safeSubstr(self::$state, 0, 4));
70
            $seed = $this->generate(Util::safeStrlen(dechex(PHP_INT_MAX)));
71
            list( , self::$counter) = unpack("i", $seed);
72
        }
73
    }
74
75
    /**
76
     * Generate a random string of the specified size
77
     *
78
     * @param int $size The size of the requested random string
79
     *
80
     * @return string A string of the requested size
81
     */
82
    public function generate($size) {
83
        $result      = '';
84
        $seed        = microtime() . memory_get_usage();
85
        self::$state = hash('sha512', self::$state . $seed, true);
86
        /**
87
         * Make the generated randomness a bit better by forcing a GC run which
88
         * should complete in a indeterminate amount of time, hence improving
89
         * the strength of the randomness a bit. It's still not crypto-safe,
90
         * but at least it's more difficult to predict.
91
         */
92
        gc_collect_cycles();
93
        for ($i = 0; $i < $size; $i += 8) {
94
            $seed = self::$state .
95
                    microtime() .
96
                    pack('Ni', $i, self::counter());
97
            self::$state = hash('sha512', $seed, true);
98
            /**
99
             * We only use the first 8 bytes here to prevent exposing the state
100
             * in its entirety, which could potentially expose other random 
101
             * generations in the future (in the same process)...
102
             */
103
            $result .= Util::safeSubstr(self::$state, 0, 8);
104
        }
105
        return Util::safeSubstr($result, 0, $size);
106
    }
107
108
    private static function counter() {
109
        if (self::$counter >= PHP_INT_MAX) {
110
            self::$counter = -1 * PHP_INT_MAX - 1;
111
        } else {
112
            self::$counter++;
113
        }
114
        return self::$counter;
115
    }
116
117
}
118