Completed
Push — master ( 9159fd...a2f733 )
by Oliver
08:55
created

OpenSslGenerator   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 85.71%

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 0
dl 0
loc 57
ccs 12
cts 14
cp 0.8571
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 6
    public function __construct($bytes = PHP_INT_SIZE, $forceStrong = true)
37
    {
38 6
        if((int)$bytes < 1) {
39 3
            throw new \OutOfRangeException('The length of the desired string of bytes. Must be a positive integer.');
40
        }
41
42 3
        $this->bytes       = (int)$bytes;
43 3
        $this->forceStrong = (bool)$forceStrong;
44 3
    }
45
46
    /**
47
     * @return bool
48
     */
49 1
    public function isForceStrong(): bool
50
    {
51 1
        return $this->forceStrong;
52
    }
53
54
    /**
55
     * @inheritdoc
56
     * @see https://php.net/manual/en/function.openssl-random-pseudo-bytes.php
57
     * @throws RuntimeException
58
     */
59 2
    public function getRandomInt()
60
    {
61 2
        $random = openssl_random_pseudo_bytes($this->bytes, $strong);
62 2
        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 2
        return hexdec(bin2hex($random));
69
    }
70
}
71