Failed Conditions
Push — v7 ( a687dc...e264c8 )
by Florent
02:28
created

RandomNumberGenerator::generate()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 8
nc 1
nop 1
1
<?php
2
3
namespace Jose\Component\Core\Util\Ecc\Random;
4
5
use Jose\Component\Core\Util\Ecc\Math\GmpMath;
6
use Jose\Component\Core\Util\Ecc\Util\NumberSize;
7
8
final class RandomNumberGenerator
9
{
10
    /**
11
     * @var GmpMath
12
     */
13
    private $adapter;
14
15
    /**
16
     * RandomNumberGenerator constructor.
17
     * @param GmpMath $adapter
18
     */
19
    public function __construct(GmpMath $adapter)
20
    {
21
        $this->adapter = $adapter;
22
    }
23
24
    /**
25
     * @param \GMP $max
26
     * @return \GMP
27
     */
28
    public function generate(\GMP $max)
29
    {
30
        $numBits = NumberSize::bnNumBits($this->adapter, $max);
31
        $numBytes = ceil($numBits / 8);
32
33
        // Generate an integer of size >= $numBits
34
        $bytes = random_bytes($numBytes);
35
        $value = $this->adapter->stringToInt($bytes);
36
37
        $mask = gmp_sub(gmp_pow(2, $numBits), 1);
38
        $integer = gmp_and($value, $mask);
39
40
        return $integer;
41
    }
42
}
43