Commit | Line | Data |
---|---|---|
14d4f286 S |
1 | <?php |
2 | /** | |
3 | * The URandom Random Number Source | |
4 | * | |
5 | * This uses the *nix /dev/urandom device to generate medium strength numbers | |
6 | * | |
7 | * PHP version 5.3 | |
8 | * | |
9 | * @category PHPCryptLib | |
10 | * @package Random | |
11 | * @subpackage Source | |
12 | * @author Anthony Ferrara <ircmaxell@ircmaxell.com> | |
13 | * @copyright 2011 The Authors | |
14 | * @license http://www.opensource.org/licenses/mit-license.html MIT License | |
15 | * @version Build @@version@@ | |
16 | */ | |
17 | ||
18 | namespace CryptLib\Random\Source; | |
19 | ||
20 | use CryptLib\Core\Strength; | |
21 | ||
22 | /** | |
23 | * The URandom Random Number Source | |
24 | * | |
25 | * This uses the *nix /dev/urandom device to generate medium strength numbers | |
26 | * | |
27 | * @category PHPCryptLib | |
28 | * @package Random | |
29 | * @subpackage Source | |
30 | * @author Anthony Ferrara <ircmaxell@ircmaxell.com> | |
31 | * @codeCoverageIgnore | |
32 | */ | |
33 | class URandom implements \CryptLib\Random\Source { | |
34 | ||
35 | /** | |
36 | * @var string The file to read from | |
37 | */ | |
38 | protected $file = '/dev/urandom'; | |
39 | ||
40 | /** | |
41 | * Return an instance of Strength indicating the strength of the source | |
42 | * | |
43 | * @return Strength An instance of one of the strength classes | |
44 | */ | |
45 | public static function getStrength() { | |
46 | return new Strength(Strength::MEDIUM); | |
47 | } | |
48 | ||
49 | /** | |
50 | * Generate a random string of the specified size | |
51 | * | |
52 | * @param int $size The size of the requested random string | |
53 | * | |
54 | * @return string A string of the requested size | |
55 | */ | |
56 | public function generate($size) { | |
57 | if ($size == 0 || !file_exists($this->file)) { | |
58 | return str_repeat(chr(0), $size); | |
59 | } | |
60 | $file = fopen($this->file, 'rb'); | |
61 | if (!$file) { | |
62 | return str_repeat(chr(0), $size); | |
63 | } | |
64 | if (function_exists('stream_set_read_buffer')) { | |
65 | stream_set_read_buffer($file, 0); | |
66 | } | |
67 | $result = fread($file, $size); | |
68 | fclose($file); | |
69 | return $result; | |
70 | } | |
71 | ||
72 | } |