summaryrefslogtreecommitdiff
path: root/src/porting.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'src/porting.cpp')
-rw-r--r--src/porting.cpp43
1 files changed, 42 insertions, 1 deletions
diff --git a/src/porting.cpp b/src/porting.cpp
index ced41d4fb..3e39fc813 100644
--- a/src/porting.cpp
+++ b/src/porting.cpp
@@ -29,6 +29,8 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include <sys/types.h>
#include <sys/sysctl.h>
#elif defined(_WIN32)
+ #include <windows.h>
+ #include <wincrypt.h>
#include <algorithm>
#endif
#if !defined(_WIN32)
@@ -701,5 +703,44 @@ v2u32 getDisplaySize()
# endif // __ANDROID__
#endif // SERVER
-} //namespace porting
+////
+//// OS-specific Secure Random
+////
+
+#ifdef WIN32
+
+bool secure_rand_fill_buf(void *buf, size_t len)
+{
+ HCRYPTPROV wctx;
+
+ if (!CryptAcquireContext(&wctx, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
+ return false;
+
+ CryptGenRandom(wctx, len, (BYTE *)buf);
+ CryptReleaseContext(wctx, 0);
+ return true;
+}
+
+#else
+
+bool secure_rand_fill_buf(void *buf, size_t len)
+{
+ // N.B. This function checks *only* for /dev/urandom, because on most
+ // common OSes it is non-blocking, whereas /dev/random is blocking, and it
+ // is exceptionally uncommon for there to be a situation where /dev/random
+ // exists but /dev/urandom does not. This guesswork is necessary since
+ // random devices are not covered by any POSIX standard...
+ FILE *fp = fopen("/dev/urandom", "rb");
+ if (!fp)
+ return false;
+
+ bool success = fread(buf, len, 1, fp) == 1;
+
+ fclose(fp);
+ return success;
+}
+
+#endif
+
+} //namespace porting