|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Riimu\Kit\SecureRandom\Generator; |
|
4
|
|
|
|
|
5
|
|
|
/** |
|
6
|
|
|
* Generates bytes reading directly from the random device. |
|
7
|
|
|
* |
|
8
|
|
|
* RandomReader generates random bytes by reading directly from the random |
|
9
|
|
|
* device (i.e. from /dev/urandom or /dev/random). |
|
10
|
|
|
* |
|
11
|
|
|
* @author Riikka Kalliomäki <[email protected]> |
|
12
|
|
|
* @copyright Copyright (c) 2014-2017 Riikka Kalliomäki |
|
13
|
|
|
* @license http://opensource.org/licenses/mit-license.php MIT License |
|
14
|
|
|
*/ |
|
15
|
|
|
class RandomReader extends AbstractGenerator |
|
16
|
|
|
{ |
|
17
|
|
|
/** @var string Path to the random device */ |
|
18
|
|
|
private $source; |
|
19
|
|
|
|
|
20
|
|
|
/** @var resource|null File pointer to the random source */ |
|
21
|
|
|
private $pointer; |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* Creates new instance of RandomReader. |
|
25
|
|
|
* @param bool $urandom True to read from /dev/urandom and false to read from /dev/random |
|
26
|
|
|
*/ |
|
27
|
10 |
|
public function __construct($urandom = true) |
|
28
|
|
|
{ |
|
29
|
10 |
|
$this->source = $urandom ? '/dev/urandom' : '/dev/random'; |
|
30
|
10 |
|
$this->pointer = null; |
|
31
|
10 |
|
} |
|
32
|
|
|
|
|
33
|
|
|
/** |
|
34
|
|
|
* Closes the file pointer. |
|
35
|
|
|
*/ |
|
36
|
10 |
|
public function __destruct() |
|
37
|
|
|
{ |
|
38
|
10 |
|
if (isset($this->pointer)) { |
|
39
|
9 |
|
fclose($this->pointer); |
|
40
|
3 |
|
} |
|
41
|
|
|
|
|
42
|
10 |
|
$this->pointer = null; |
|
43
|
10 |
|
} |
|
44
|
|
|
|
|
45
|
10 |
|
public function isSupported() |
|
46
|
|
|
{ |
|
47
|
10 |
|
return is_readable($this->source); |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
9 |
|
protected function readBytes($count) |
|
51
|
|
|
{ |
|
52
|
9 |
|
return fread($this->getPointer(), $count); |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
/** |
|
56
|
|
|
* Returns the pointer to the random source. |
|
57
|
|
|
* @return resource The pointer to the random source |
|
58
|
|
|
*/ |
|
59
|
9 |
|
private function getPointer() |
|
60
|
|
|
{ |
|
61
|
9 |
|
if (!isset($this->pointer)) { |
|
62
|
9 |
|
$this->pointer = fopen($this->source, 'r'); |
|
63
|
|
|
|
|
64
|
|
|
// File read buffering is not supported on HHVM |
|
65
|
9 |
|
if (!defined('HHVM_VERSION')) { |
|
66
|
9 |
|
stream_set_chunk_size($this->pointer, 32); |
|
67
|
9 |
|
stream_set_read_buffer($this->pointer, 32); |
|
68
|
3 |
|
} |
|
69
|
3 |
|
} |
|
70
|
|
|
|
|
71
|
9 |
|
return $this->pointer; |
|
72
|
|
|
} |
|
73
|
|
|
} |
|
74
|
|
|
|