|
8 | 8 |
|
9 | 9 | class RandomGenerator |
10 | 10 | { |
11 | | - protected ?LoggerInterface $logger; |
12 | | - protected bool $useOpenSsl; |
13 | | - |
14 | | - /** |
15 | | - * @param LoggerInterface|null $logger |
16 | | - */ |
17 | | - public function __construct(LoggerInterface $logger = null) |
| 11 | + public function __construct(protected readonly LoggerInterface $logger) |
18 | 12 | { |
19 | | - $this->logger = $logger; |
20 | | - // determine whether to use OpenSSL |
21 | | - if (defined('PHP_WINDOWS_VERSION_BUILD') && version_compare(PHP_VERSION, '5.3.4', '<')) { |
22 | | - $this->useOpenSsl = false; |
23 | | - } elseif (!function_exists('openssl_random_pseudo_bytes')) { |
24 | | - if (null !== $this->logger) { |
25 | | - $this->logger->notice('It is recommended that you enable the "openssl" extension for random number generation.'); |
26 | | - } |
27 | | - $this->useOpenSsl = false; |
28 | | - } else { |
29 | | - $this->useOpenSsl = true; |
| 13 | + if (!function_exists('openssl_random_pseudo_bytes')) { |
| 14 | + throw new \RuntimeException('You must enable the "openssl" extension for secure random number generation.'); |
30 | 15 | } |
31 | 16 | } |
32 | 17 |
|
33 | | - /** |
34 | | - * @param int $nbBytes |
35 | | - * @return string |
36 | | - */ |
37 | 18 | public function getRandomNumber(int $nbBytes = 32): string |
38 | 19 | { |
39 | 20 | // try OpenSSL |
40 | | - if ($this->useOpenSsl) { |
41 | | - $bytes = \openssl_random_pseudo_bytes($nbBytes, $strong); |
42 | | - |
43 | | - if (false !== $bytes && true === $strong) { |
44 | | - return $bytes; |
45 | | - } |
| 21 | + $bytes = \openssl_random_pseudo_bytes($nbBytes, $strong); |
46 | 22 |
|
47 | | - if (null !== $this->logger) { |
48 | | - $this->logger->info('OpenSSL did not produce a secure random number.'); |
49 | | - } |
| 23 | + if (false !== $bytes && true === $strong) { |
| 24 | + return $bytes; |
50 | 25 | } |
51 | 26 |
|
52 | | - return hash('sha256', uniqid((string) mt_rand(), true), true); |
| 27 | + throw new \RuntimeException('Unable to generate a secure random number.'); |
53 | 28 | } |
54 | 29 | } |
0 commit comments