aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib/rng/system_rng
diff options
context:
space:
mode:
Diffstat (limited to 'src/lib/rng/system_rng')
-rw-r--r--src/lib/rng/system_rng/info.txt19
-rw-r--r--src/lib/rng/system_rng/system_rng.cpp79
-rw-r--r--src/lib/rng/system_rng/system_rng.h19
3 files changed, 117 insertions, 0 deletions
diff --git a/src/lib/rng/system_rng/info.txt b/src/lib/rng/system_rng/info.txt
new file mode 100644
index 000000000..387b7e1dd
--- /dev/null
+++ b/src/lib/rng/system_rng/info.txt
@@ -0,0 +1,19 @@
+define SYSTEM_RNG 20141202
+
+<os>
+aix
+cygwin
+darwin
+dragonfly
+freebsd
+haiku
+hpux
+hurd
+irix
+linux
+netbsd
+openbsd
+qnx
+solaris
+tru64
+</os>
diff --git a/src/lib/rng/system_rng/system_rng.cpp b/src/lib/rng/system_rng/system_rng.cpp
new file mode 100644
index 000000000..afffb69cc
--- /dev/null
+++ b/src/lib/rng/system_rng/system_rng.cpp
@@ -0,0 +1,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;
+ }
+
+}
diff --git a/src/lib/rng/system_rng/system_rng.h b/src/lib/rng/system_rng/system_rng.h
new file mode 100644
index 000000000..6b4746a9c
--- /dev/null
+++ b/src/lib/rng/system_rng/system_rng.h
@@ -0,0 +1,19 @@
+/*
+* System RNG interface
+* (C) 2014 Jack Lloyd
+*
+* Distributed under the terms of the Botan license
+*/
+
+#ifndef BOTAN_SYSTEM_RNG_H__
+#define BOTAN_SYSTEM_RNG_H__
+
+#include <botan/rng.h>
+
+namespace Botan {
+
+BOTAN_DLL RandomNumberGenerator& system_rng();
+
+}
+
+#endif