Completed
Push — master ( db8df2...9159fd )
by Oliver
13:47
created

OpenSslGenerator::isForceStrong()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1.125

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 4
cp 0.5
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 1.125
1
<?php
2
3
namespace TQ\Shamir\Random;
4
5
use RuntimeException;
6
7
/**
8
 * Class OpenSslGenerator
9
 *
10
 * Generate a pseudo-random string of bytes using the OpenSSL library.
11
 *
12
 * @package TQ\Shamir\Random
13
 */
14
class OpenSslGenerator implements Generator
15
{
16
    /**
17
     * Length of the desired string of bytes
18
     *
19
     * @var int
20
     */
21
    protected $bytes = PHP_INT_SIZE;
22
23
    /**
24
     * Force strong random number generation or "die"
25
     *
26
     * @var bool
27
     */
28
    protected $forceStrong = true;
29
30
    /**
31
     * Constructor
32
     *
33
     * @param  int   $bytes        Bytes to use in result
34
     * @param  bool  $forceStrong  Force strong random number generation
35
     */
36 2
    public function __construct($bytes = PHP_INT_SIZE, $forceStrong = true)
37
    {
38 2
        if((int)$bytes < 1) {
39 2
            throw new \OutOfRangeException('The length of the desired string of bytes. Must be a positive integer.');
40 2
        }
41
42
        $this->bytes       = (int)$bytes;
43
        $this->forceStrong = (bool)$forceStrong;
44
    }
45
46
    /**
47 2
     * @return bool
48
     */
49 2
    public function isForceStrong(): bool
50 2
    {
51
        return $this->forceStrong;
52
    }
53
54
    /**
55
     * @inheritdoc
56 2
     * @see https://php.net/manual/en/function.openssl-random-pseudo-bytes.php
57
     * @throws RuntimeException
58
     */
59
    public function getRandomInt()
60
    {
61
        $random = openssl_random_pseudo_bytes($this->bytes, $strong);
62
        if ($random === false || ($this->forceStrong && $strong !== true)) {
63
            throw new RuntimeException(
64
                'Random number generator algorithm didn\'t used "cryptographically strong" method.'
65
            );
66
        }
67
68
        return hexdec(bin2hex($random));
69
    }
70
}
71