summaryrefslogtreecommitdiff
path: root/src/porting.cpp
diff options
context:
space:
mode:
authorest31 <MTest31@outlook.com>2015-08-06 08:57:13 +0200
committerkwolekr <kwolekr@minetest.net>2015-11-08 15:57:15 -0500
commitad5ac39d8d1a8b8f6f0fe077e20bac914ddc624b (patch)
tree6d30b2687f6c0ed60c22e626be9c31ba64a8efd7 /src/porting.cpp
parentd506d567075914b138ca869981f2e45ce503ee5d (diff)
downloadminetest-ad5ac39d8d1a8b8f6f0fe077e20bac914ddc624b.tar.gz
minetest-ad5ac39d8d1a8b8f6f0fe077e20bac914ddc624b.tar.bz2
minetest-ad5ac39d8d1a8b8f6f0fe077e20bac914ddc624b.zip
Add LuaSecureRandom
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