From a345ecd14505b1d3808a91a9dfa5a53a0edacbde Mon Sep 17 00:00:00 2001 From: Nicolas Noble Date: Fri, 9 Aug 2013 15:12:08 -0700 Subject: Trying to come up with a more cross-platform secure random number generator. --- lcrypt/lcrypt.c | 46 ++++++++++++++++++++++++++++++++++------------ 1 file changed, 34 insertions(+), 12 deletions(-) (limited to 'lcrypt') 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; -- cgit v1.2.3