1 | <?php |
||
29 | final class Random |
||
30 | { |
||
31 | |||
32 | /** |
||
33 | * Get random bytes from Mcrypt |
||
34 | * |
||
35 | * @param int $bytes Number of bytes to get |
||
36 | * |
||
37 | * @return string |
||
38 | */ |
||
39 | 14 | private static function fromMcrypt($bytes) |
|
40 | { |
||
41 | 14 | $ret = \mcrypt_create_iv($bytes, MCRYPT_DEV_URANDOM); |
|
42 | |||
43 | 14 | if ($ret === false) { |
|
44 | self::toss(); // @codeCoverageIgnore |
||
45 | } |
||
46 | |||
47 | 14 | return $ret; |
|
48 | } |
||
49 | |||
50 | /** |
||
51 | * Return securely generated random bytes. |
||
52 | * |
||
53 | * @param int $bytes Number of bytes to get |
||
54 | * |
||
55 | * @return string |
||
56 | */ |
||
57 | 14 | public static function bytes($bytes) |
|
58 | { |
||
59 | 14 | if (\function_exists('random_bytes')) { |
|
60 | return \random_bytes($bytes); |
||
61 | 14 | } elseif (\function_exists('mcrypt_create_iv')) { |
|
62 | 14 | return self::fromMcrypt($bytes); |
|
63 | } |
||
64 | |||
65 | self::toss(); |
||
66 | } |
||
67 | |||
68 | /* |
||
69 | * Throw an error when a failure occurs. |
||
70 | */ |
||
71 | |||
72 | private static function toss() |
||
79 | |||
80 | } |
||
81 |