diff options
author | Nicolas Noble <pixel@nobis-crew.org> | 2013-08-09 15:12:08 -0700 |
---|---|---|
committer | Nicolas Noble <pixel@nobis-crew.org> | 2013-08-09 15:12:08 -0700 |
commit | a345ecd14505b1d3808a91a9dfa5a53a0edacbde (patch) | |
tree | 50e06f85776b3bb39cfe761680dd104b1fd4a5a8 /lcrypt | |
parent | 316907b08ac47efc37845ec5d66f098fcae70a1a (diff) |
Trying to come up with a more cross-platform secure random number generator.
Diffstat (limited to 'lcrypt')
-rw-r--r-- | lcrypt/lcrypt.c | 46 |
1 files changed, 34 insertions, 12 deletions
diff --git a/lcrypt/lcrypt.c b/lcrypt/lcrypt.c index 620c88b..a0a45e5 100644 --- a/lcrypt/lcrypt.c +++ b/lcrypt/lcrypt.c @@ -221,20 +221,42 @@ static int lcrypt_time(lua_State *L) static int lcrypt_random(lua_State *L) { int len = luaL_checkint(L, 1); - FILE *fp; char *buffer = lcrypt_malloc(L, len); - if(unlikely((fp = fopen("/dev/urandom", "rb")) == NULL)) - { - lua_pushstring(L, "Unable to open /dev/urandom."); - (void)lua_error(L); - } - if(unlikely(fread(buffer, len, 1, fp) != 1)) - { + #ifdef _WIN32 + HMODULE hLib = LoadLibrary("ADVAPI32.DLL"); + if (unlikely(!hLib)) + { + lua_pushstring(L, "Unable to open ADVAPI32.DLL"); + (void)lua_error(L); + } + BOOLEAN (APIENTRY *pfn)(void *, ULONG) = + (BOOLEAN (APIENTRY *)(void *, ULONG)) GetProcAddress(hLib, "SystemFunction036"); + if (unlikely(!pfn)) + { + lua_pushstring(L, "Unable to open ADVAPI32.DLL"); + (void)lua_error(L); + } + ULONG ulCbBuff = len; + if (unlikely(!pfn(buffer, ulCbBuff))) + { + lua_pushstring(L, "Call to SystemFunction036 failed."); + (void)lua_error(L); + } + #else + FILE *fp; + if(unlikely((fp = fopen("/dev/urandom", "rb")) == NULL)) + { + lua_pushstring(L, "Unable to open /dev/urandom."); + (void)lua_error(L); + } + if(unlikely(fread(buffer, len, 1, fp) != 1)) + { + fclose(fp); + lua_pushstring(L, "Unable to read /dev/urandom."); + (void)lua_error(L); + } fclose(fp); - lua_pushstring(L, "Unable to read /dev/urandom."); - (void)lua_error(L); - } - fclose(fp); + #endif lua_pushlstring(L, buffer, len); free(buffer); return 1; |