|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/* |
|
4
|
|
|
* The RandomLib library for securely generating random numbers and strings in PHP |
|
5
|
|
|
* |
|
6
|
|
|
* @author Anthony Ferrara <[email protected]> |
|
7
|
|
|
* @copyright 2011 The Authors |
|
8
|
|
|
* @license http://www.opensource.org/licenses/mit-license.html MIT License |
|
9
|
|
|
* @version Build @@version@@ |
|
10
|
|
|
*/ |
|
11
|
|
|
|
|
12
|
|
|
/** |
|
13
|
|
|
* The PHP7 Random Number Source |
|
14
|
|
|
* |
|
15
|
|
|
* This uses the inbuilt PHP7 Random Bytes function |
|
16
|
|
|
* |
|
17
|
|
|
* PHP version 5.3 |
|
18
|
|
|
* |
|
19
|
|
|
* @category PHPCryptLib |
|
20
|
|
|
* @package Random |
|
21
|
|
|
* @subpackage Source |
|
22
|
|
|
* |
|
23
|
|
|
* @author Anthony Ferrara <[email protected]> |
|
24
|
|
|
* @copyright 2011 The Authors |
|
25
|
|
|
* @license http://www.opensource.org/licenses/mit-license.html MIT License |
|
26
|
|
|
* |
|
27
|
|
|
* @version Build @@version@@ |
|
28
|
|
|
*/ |
|
29
|
|
|
namespace RandomLib\Source; |
|
30
|
|
|
|
|
31
|
|
|
use SecurityLib\Strength; |
|
32
|
|
|
|
|
33
|
|
|
/** |
|
34
|
|
|
* The PHP7 Random Number Source |
|
35
|
|
|
* |
|
36
|
|
|
* This uses the php7 secure generator to generate high strength numbers |
|
37
|
|
|
* |
|
38
|
|
|
* @category PHPCryptLib |
|
39
|
|
|
* @package Random |
|
40
|
|
|
* @subpackage Source |
|
41
|
|
|
* |
|
42
|
|
|
* @author Anthony Ferrara <[email protected]> |
|
43
|
|
|
*/ |
|
44
|
|
|
class RandomBytes extends \RandomLib\AbstractSource |
|
45
|
|
|
{ |
|
46
|
|
|
|
|
47
|
|
|
/** |
|
48
|
|
|
* If the source is currently available. |
|
49
|
|
|
* Reasons might be because the library is not installed |
|
50
|
|
|
* |
|
51
|
|
|
* @return bool |
|
52
|
|
|
*/ |
|
53
|
|
|
public static function isSupported() |
|
54
|
|
|
{ |
|
55
|
|
|
return function_exists('random_bytes'); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
/** |
|
59
|
|
|
* Return an instance of Strength indicating the strength of the source |
|
60
|
|
|
* |
|
61
|
|
|
* @return Strength An instance of one of the strength classes |
|
62
|
|
|
*/ |
|
63
|
|
|
public static function getStrength() |
|
64
|
|
|
{ |
|
65
|
|
|
return new Strength(Strength::HIGH); |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
/** |
|
69
|
|
|
* Generate a random string of the specified size |
|
70
|
|
|
* |
|
71
|
|
|
* @param int $size The size of the requested random string |
|
72
|
|
|
* |
|
73
|
|
|
* @return string A string of the requested size |
|
74
|
|
|
*/ |
|
75
|
|
|
public function generate($size) |
|
76
|
|
|
{ |
|
77
|
|
|
if (!self::isSupported()) { |
|
78
|
|
|
return str_repeat(chr(0), $size); |
|
79
|
|
|
} |
|
80
|
|
|
|
|
81
|
|
|
return \random_bytes($size); |
|
82
|
|
|
} |
|
83
|
|
|
} |
|
84
|
|
|
|