MicroTime::__construct()   B
last analyzed

Complexity

Conditions 6
Paths 16

Size

Total Lines 23
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 10
Bugs 1 Features 4
Metric Value
c 10
b 1
f 4
dl 0
loc 23
rs 8.5906
cc 6
eloc 17
nc 16
nop 0
1
<?php
2
3
/*
4
 * The RandomLib library for securely generating random numbers and strings in PHP
5
 *
6
 * @author     Anthony Ferrara <[email protected]>
7
 * @copyright  2011 The Authors
8
 * @license    http://www.opensource.org/licenses/mit-license.html  MIT License
9
 * @version    Build @@version@@
10
 */
11
12
/**
13
 * The Microtime Random Number Source
14
 *
15
 * This uses the current micro-second (looped several times) for a **very** weak
16
 * random number source.  This is only useful when combined with several other
17
 * stronger sources
18
 *
19
 * PHP version 5.3
20
 *
21
 * @category   PHPCryptLib
22
 * @package    Random
23
 * @subpackage Source
24
 *
25
 * @author     Anthony Ferrara <[email protected]>
26
 * @copyright  2011 The Authors
27
 * @license    http://www.opensource.org/licenses/mit-license.html  MIT License
28
 *
29
 * @version    Build @@version@@
30
 */
31
namespace RandomLib\Source;
32
33
use SecurityLib\Strength;
34
use SecurityLib\Util;
35
36
/**
37
 * The Microtime Random Number Source
38
 *
39
 * This uses the current micro-second (looped several times) for a **very** weak
40
 * random number source.  This is only useful when combined with several other
41
 * stronger sources
42
 *
43
 * @category   PHPCryptLib
44
 * @package    Random
45
 * @subpackage Source
46
 *
47
 * @author     Anthony Ferrara <[email protected]>
48
 * @codeCoverageIgnore
49
 */
50
final class MicroTime extends \RandomLib\AbstractSource
51
{
52
53
    /**
54
     * A static counter to ensure unique hashes and prevent state collisions
55
     *
56
     * @var int A counter
57
     */
58
    private static $counter = null;
59
60
    /**
61
     * The current state of the random number generator.
62
     *
63
     * @var string The state of the PRNG
64
     */
65
    private static $state = '';
66
67
    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...
68
    {
69
        $state = self::$state;
70
        if (function_exists('posix_times')) {
71
            $state .= serialize(posix_times());
72
        }
73
        if (!defined('HHVM_VERSION') && function_exists('zend_thread_id')) {
74
            $state .= zend_thread_id();
75
        }
76
        if (function_exists('hphp_get_thread_id')) {
77
            $state .= hphp_get_thread_id();
78
        }
79
        $state      .= getmypid() . memory_get_usage();
80
        $state      .= serialize($_ENV);
81
        $state      .= serialize($_SERVER);
82
        $state      .= count(debug_backtrace(false));
83
        self::$state = hash('sha512', $state, true);
84
        if (is_null(self::$counter)) {
85
            list(, self::$counter) = unpack("i", Util::safeSubstr(self::$state, 0, 4));
86
            $seed = $this->generate(Util::safeStrlen(dechex(PHP_INT_MAX)));
87
            list(, self::$counter) = unpack("i", $seed);
88
        }
89
    }
90
91
    /**
92
     * Generate a random string of the specified size
93
     *
94
     * @param int $size The size of the requested random string
95
     *
96
     * @return string A string of the requested size
97
     */
98
    public function generate($size)
99
    {
100
        $result      = '';
101
        $seed        = microtime() . memory_get_usage();
102
        self::$state = hash('sha512', self::$state . $seed, true);
103
        /**
104
         * Make the generated randomness a bit better by forcing a GC run which
105
         * should complete in a indeterminate amount of time, hence improving
106
         * the strength of the randomness a bit. It's still not crypto-safe,
107
         * but at least it's more difficult to predict.
108
         */
109
        gc_collect_cycles();
110
        for ($i = 0; $i < $size; $i += 8) {
111
            $seed = self::$state .
112
                    microtime() .
113
                    pack('Ni', $i, self::counter());
114
            self::$state = hash('sha512', $seed, true);
115
            /**
116
             * We only use the first 8 bytes here to prevent exposing the state
117
             * in its entirety, which could potentially expose other random
118
             * generations in the future (in the same process)...
119
             */
120
            $result .= Util::safeSubstr(self::$state, 0, 8);
121
        }
122
123
        return Util::safeSubstr($result, 0, $size);
124
    }
125
126
    private static function counter()
127
    {
128
        if (self::$counter >= PHP_INT_MAX) {
129
            self::$counter = -1 * PHP_INT_MAX - 1;
130
        } else {
131
            self::$counter++;
132
        }
133
134
        return self::$counter;
135
    }
136
}
137