From ad5ac39d8d1a8b8f6f0fe077e20bac914ddc624b Mon Sep 17 00:00:00 2001 From: est31 Date: Thu, 6 Aug 2015 08:57:13 +0200 Subject: Add LuaSecureRandom --- src/porting.cpp | 43 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 42 insertions(+), 1 deletion(-) (limited to 'src/porting.cpp') 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 #include #elif defined(_WIN32) + #include + #include #include #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 -- cgit v1.2.3