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

OpenSslGenerator   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 80%

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 0
dl 0
loc 57
ccs 8
cts 10
cp 0.8
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 2
A isForceStrong() 0 4 1
A getRandomInt() 0 11 4
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