|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* Random.php |
|
5
|
|
|
* |
|
6
|
|
|
* PHP version 5 |
|
7
|
|
|
* |
|
8
|
|
|
* @category Dcrypt |
|
9
|
|
|
* @package Dcrypt |
|
10
|
|
|
* @author Michael Meyer (mmeyer2k) <[email protected]> |
|
11
|
|
|
* @license http://opensource.org/licenses/MIT The MIT License (MIT) |
|
12
|
|
|
* @link https://github.com/mmeyer2k/dcrypt |
|
13
|
|
|
* @link https://apigen.ci/github/mmeyer2k/dcrypt |
|
14
|
|
|
*/ |
|
15
|
|
|
|
|
16
|
|
|
namespace Dcrypt; |
|
17
|
|
|
|
|
18
|
|
|
/** |
|
19
|
|
|
* Fail-safe wrapper for mcrypt_create_iv (preferably) and |
|
20
|
|
|
* openssl_random_pseudo_bytes (fallback). |
|
21
|
|
|
* |
|
22
|
|
|
* @category Dcrypt |
|
23
|
|
|
* @package Dcrypt |
|
24
|
|
|
* @author Michael Meyer (mmeyer2k) <[email protected]> |
|
25
|
|
|
* @license http://opensource.org/licenses/MIT The MIT License (MIT) |
|
26
|
|
|
* @link https://github.com/mmeyer2k/dcrypt |
|
27
|
|
|
* @link https://apigen.ci/github/mmeyer2k/dcrypt/class-Dcrypt.Random.html |
|
28
|
|
|
*/ |
|
29
|
|
|
final class Random |
|
30
|
|
|
{ |
|
31
|
|
|
/** |
|
32
|
|
|
* Get random bytes from Mcrypt |
|
33
|
|
|
* |
|
34
|
|
|
* @param int $bytes Number of bytes to get |
|
35
|
|
|
* |
|
36
|
|
|
* @return string |
|
37
|
|
|
*/ |
|
38
|
19 |
|
private static function fromMcrypt($bytes) |
|
39
|
|
|
{ |
|
40
|
19 |
|
$ret = \mcrypt_create_iv($bytes, MCRYPT_DEV_URANDOM); |
|
41
|
|
|
|
|
42
|
19 |
|
if ($ret === false) { |
|
43
|
|
|
self::toss(); // @codeCoverageIgnore |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
19 |
|
return $ret; |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
/** |
|
50
|
|
|
* Return securely generated random bytes. |
|
51
|
|
|
* |
|
52
|
|
|
* @param int $bytes Number of bytes to get |
|
53
|
|
|
* |
|
54
|
|
|
* @return string |
|
55
|
|
|
*/ |
|
56
|
19 |
|
public static function bytes($bytes) |
|
57
|
|
|
{ |
|
58
|
19 |
|
if (\function_exists('random_bytes')) { |
|
59
|
|
|
return \random_bytes($bytes); |
|
60
|
19 |
|
} elseif (\function_exists('mcrypt_create_iv')) { |
|
61
|
19 |
|
return self::fromMcrypt($bytes); |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
self::toss(); // @codeCoverageIgnore |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
|
|
/** |
|
68
|
|
|
* Throw an error when a failure occurs. |
|
69
|
|
|
* |
|
70
|
|
|
* @codeCoverageIgnore |
|
71
|
|
|
*/ |
|
72
|
|
|
private static function toss() |
|
73
|
|
|
{ |
|
74
|
|
|
$e = 'Dcrypt failed to generate a random number'; |
|
75
|
|
|
throw new \exception($e); |
|
76
|
|
|
} |
|
77
|
|
|
} |