Rand::SecureInt()   C
last analyzed

Complexity

Conditions 11
Paths 66

Size

Total Lines 64
Code Lines 40

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 1
Metric Value
c 3
b 0
f 1
dl 0
loc 64
rs 6.0563
cc 11
eloc 40
nc 66
nop 3

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Part of twLib
4
 * http://www.thomaswhiston.com
5
 * [email protected]
6
 * Created by PhpStorm.
7
 * User: Thomas Whiston
8
 * Date: 04/01/2016
9
 * Time: 23:04
10
 */
11
namespace twhiston\twLib\Rand;
12
13
/**
14
 * Class Rand
15
 * Generate random ints within range or random string
16
 * Will always try to use php7 functions where possible, but if earlier only semi secure int generation is possible
17
 * @package twhiston\twLib
18
 * @deprecated use the symfony polyfill for real secure numbers
19
 */
20
class Rand
21
{
22
23
24
    /**
25
     * Generate random int or throws exception. NON SECURE
26
     * @param $min
27
     * @param $max
28
     * @return int|null
29
     * @throws \twhiston\twLib\TwLibException
30
     */
31
    static public function Int($min, $max)
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
32
    {
33
34
        //Ensure order correctness
35
        if ($min > $max) {
36
            $temp = $max;
37
            $max = $min;
38
            $min = $temp;
39
        }
40
        $rand = null;
41
        if (phpversion() >= 7) {
42
            //random_int is php7 only
43
            try {
44
                $rand = \random_int($min, $max);
45
            } catch (\Exception $e) {
46
                $rand = \mt_rand($min, $max);
47
            }
48
        } else {
49
            $rand = \mt_rand($min, $max);
50
        }
51
52
        if ($rand === null) {
53
            //We must not be NULL here, we could be 0, but if we are NULL then something went wrong with generation
54
            throw new TwLibException('Rand could not be generated');
55
        }
56
57
        return $rand;
58
    }
59
60
    /**
61
     * Manual secure int version based on http://stackoverflow.com/questions/1313223/replace-rand-with-openssl-random-pseudo-bytes SECURE-ish
62
     * @param $min
63
     * @param $max
64
     * @param bool|TRUE $pedantic
65
     * @return int|null
66
     * @throws \twhiston\twLib\TwLibException
67
     */
68
    static public function SecureInt($min, $max, $pedantic = true)
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
69
    {
70
71
        //Ensure order correctness
72
        if ($min > $max) {
73
            $temp = $max;
74
            $max = $min;
75
            $min = $temp;
76
        }
77
        $rand = null;
78
        $manual = true;
79
        if (phpversion() >= 7) {
80
            try {
81
                $rand = random_int($min, $max);
82
                $manual = false;
83
            } catch (\Exception $e) {
84
                $manual = true;
85
            }
86
        }
87
88
        if ($manual === true) {
89
            //http://stackoverflow.com/questions/1313223/replace-rand-with-openssl-random-pseudo-bytes
90
            $secure = false;
91
            $diff = $max - $min;
92
            if ($diff <= 0) {
93
                return $min;
94
            } // not so random...
95
            $range = $diff + 1; // because $max is inclusive
96
            $bits = ceil(log(($range), 2));
97
            $bytes = ceil($bits / 8.0);
98
            $bits_max = 1 << $bits;
99
            // e.g. if $range = 3000 (bin: 101110111000)
100
            //  +--------+--------+
101
            //  |....1011|10111000|
0 ignored issues
show
Unused Code Comprehensibility introduced by
86% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
102
            //  +--------+--------+
103
            //  bits=12, bytes=2, bits_max=2^12=4096
0 ignored issues
show
Unused Code Comprehensibility introduced by
45% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
104
            $num = 0;
0 ignored issues
show
Unused Code introduced by
$num is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
105
            do {
106
                $num = hexdec(
107
                        bin2hex(openssl_random_pseudo_bytes($bytes, $secure))
108
                    ) % $bits_max;
109
                if ($secure === false) {
110
                    throw new TwLibException(
111
                        'Non secure value generated. This is a system issue'
112
                    );
113
                }
114
                if ($num >= $range) {
115
                    if ($pedantic) {
116
                        continue;
117
                    } // start over instead of accepting bias
118
                    // else
119
                    $num = $num % $range;  // to hell with security
120
                }
121
                break;
122
            } while (true);
123
            $rand = $num + $min;
124
        }
125
        if ($rand === null) {
126
            //We must not be NULL here, we could be 0, but if we are NULL then something went wrong with generation
127
            throw new TwLibException('Rand could not be generated');
128
        }
129
130
        return $rand;
131
    }
132
133
    /**
134
     * Generate a random string of length. SECURE
135
     * @param $length
136
     * @return null|string
137
     * @throws \twhiston\twLib\TwLibException if string is generated non securely or result is null
138
     */
139
    static public function String($length)
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
140
    {
141
142
        $string = null;
0 ignored issues
show
Unused Code introduced by
$string is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
143
        $length /= 2;
144
        if (phpversion() >= 7) {
145
            $string = bin2hex(random_bytes($length));
146
        } else {
147
            $secure = false;
148
            $string = bin2hex(openssl_random_pseudo_bytes($length, $secure));
149
            if ($secure === false) {
150
                throw new TwLibException(
151
                    'Non secure string generated. This is a system issue'
152
                );
153
            }
154
        }
155
156
        if ($string === null) {
157
            throw new TwLibException('Random string is NULL, PANIC');
158
        }
159
160
        return $string;
161
162
    }
163
164
}