1
0
Fork 0
mirror of https://github.com/luanti-org/luanti.git synced 2025-06-27 16:36:03 +00:00

Add LuaSecureRandom

This commit is contained in:
est31 2015-08-06 08:57:13 +02:00 committed by kwolekr
parent d506d56707
commit ad5ac39d8d
6 changed files with 201 additions and 1 deletions

View file

@ -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