Matthias Andreas Benkard | b382b10 | 2021-01-02 15:32:21 +0100 | [diff] [blame] | 1 | <?php |
| 2 | |
| 3 | namespace RobThree\Auth\Providers\Rng; |
| 4 | |
| 5 | class OpenSSLRNGProvider implements IRNGProvider |
| 6 | { |
Matthias Andreas Benkard | 7b2a3a1 | 2021-08-16 10:57:25 +0200 | [diff] [blame^] | 7 | /** @var bool */ |
Matthias Andreas Benkard | b382b10 | 2021-01-02 15:32:21 +0100 | [diff] [blame] | 8 | private $requirestrong; |
Matthias Andreas Benkard | 7b2a3a1 | 2021-08-16 10:57:25 +0200 | [diff] [blame^] | 9 | |
| 10 | /** |
| 11 | * @param bool $requirestrong |
| 12 | */ |
| 13 | public function __construct($requirestrong = true) |
| 14 | { |
Matthias Andreas Benkard | b382b10 | 2021-01-02 15:32:21 +0100 | [diff] [blame] | 15 | $this->requirestrong = $requirestrong; |
| 16 | } |
Matthias Andreas Benkard | 7b2a3a1 | 2021-08-16 10:57:25 +0200 | [diff] [blame^] | 17 | |
| 18 | /** |
| 19 | * {@inheritdoc} |
| 20 | */ |
| 21 | public function getRandomBytes($bytecount) |
| 22 | { |
Matthias Andreas Benkard | b382b10 | 2021-01-02 15:32:21 +0100 | [diff] [blame] | 23 | $result = openssl_random_pseudo_bytes($bytecount, $crypto_strong); |
Matthias Andreas Benkard | 7b2a3a1 | 2021-08-16 10:57:25 +0200 | [diff] [blame^] | 24 | if ($this->requirestrong && ($crypto_strong === false)) { |
| 25 | throw new RNGException('openssl_random_pseudo_bytes returned non-cryptographically strong value'); |
| 26 | } |
| 27 | if ($result === false) { |
| 28 | throw new RNGException('openssl_random_pseudo_bytes returned an invalid value'); |
| 29 | } |
Matthias Andreas Benkard | b382b10 | 2021-01-02 15:32:21 +0100 | [diff] [blame] | 30 | return $result; |
| 31 | } |
Matthias Andreas Benkard | 7b2a3a1 | 2021-08-16 10:57:25 +0200 | [diff] [blame^] | 32 | |
| 33 | /** |
| 34 | * {@inheritdoc} |
| 35 | */ |
| 36 | public function isCryptographicallySecure() |
| 37 | { |
Matthias Andreas Benkard | b382b10 | 2021-01-02 15:32:21 +0100 | [diff] [blame] | 38 | return $this->requirestrong; |
| 39 | } |
Matthias Andreas Benkard | 7b2a3a1 | 2021-08-16 10:57:25 +0200 | [diff] [blame^] | 40 | } |