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