blob: afffb69cc0a8b0a4292d720d2f8db51276d81236 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
|
/*
* System RNG
* (C) 2014 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/
#include <botan/system_rng.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
namespace Botan {
namespace {
class System_RNG : public RandomNumberGenerator
{
public:
System_RNG();
~System_RNG();
void randomize(byte buf[], size_t len);
bool is_seeded() const { return true; }
void clear() {}
std::string name() const { return "system"; }
void reseed(size_t) {}
void add_entropy(const byte[], size_t) {}
private:
int m_fd;
};
System_RNG::System_RNG()
{
m_fd = ::open("/dev/urandom", O_RDONLY);
if(m_fd < 0)
throw std::runtime_error("System_RNG failed to open /dev/urandom");
}
System_RNG::~System_RNG()
{
::close(m_fd);
}
void System_RNG::randomize(byte buf[], size_t len)
{
while(len)
{
ssize_t got = ::read(m_fd, buf, len);
if(got < 0)
{
if(errno == EINTR)
continue;
throw std::runtime_error("System_RNG read failed error " + std::to_string(errno));
}
if(got == 0)
throw std::runtime_error("System_RNG EOF on device"); // ?!?
buf += got;
len -= got;
}
}
}
RandomNumberGenerator& system_rng()
{
static System_RNG g_system_rng;
return g_system_rng;
}
}
|