diff --git a/mongoose.c b/mongoose.c index 6ca87542..338d35e5 100644 --- a/mongoose.c +++ b/mongoose.c @@ -16388,15 +16388,16 @@ bool mg_random(void *buf, size_t len) { success = CryptGenRandom(hProv, len, p); } #else - // BCrypt is a "new generation" strong crypto API, so try it first - static BCRYPT_ALG_HANDLE hProv; - if (initialised == false && - BCryptOpenAlgorithmProvider(&hProv, BCRYPT_RNG_ALGORITHM, NULL, 0) == 0) { - initialised = true; - } - if (initialised == true) { - success = BCryptGenRandom(hProv, p, (ULONG) len, 0) == 0; + size_t i; + for (i = 0; i < len; i++) { + unsigned int rand_v; + if (rand_s(&rand_v) == 0) { + p[i] = (unsigned char)(rand_v & 255); + } else { + break; + } } + success = (i == len); #endif #elif MG_ARCH == MG_ARCH_UNIX diff --git a/mongoose.h b/mongoose.h index af8e76fe..72fef7ac 100644 --- a/mongoose.h +++ b/mongoose.h @@ -415,6 +415,10 @@ static inline int mg_mkdir(const char *path, mode_t mode) { #if MG_ARCH == MG_ARCH_WIN32 +#ifndef _CRT_RAND_S +#define _CRT_RAND_S +#endif + #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif @@ -470,11 +474,6 @@ typedef enum { false = 0, true = 1 } bool; #endif #include #pragma comment(lib, "advapi32.lib") -#else -#include -#if defined(_MSC_VER) -#pragma comment(lib, "bcrypt.lib") -#endif #endif // Protect from calls like std::snprintf in app code diff --git a/src/arch_win32.h b/src/arch_win32.h index c31310f3..78948d88 100644 --- a/src/arch_win32.h +++ b/src/arch_win32.h @@ -2,6 +2,10 @@ #if MG_ARCH == MG_ARCH_WIN32 +#ifndef _CRT_RAND_S +#define _CRT_RAND_S +#endif + #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif @@ -57,11 +61,6 @@ typedef enum { false = 0, true = 1 } bool; #endif #include #pragma comment(lib, "advapi32.lib") -#else -#include -#if defined(_MSC_VER) -#pragma comment(lib, "bcrypt.lib") -#endif #endif // Protect from calls like std::snprintf in app code diff --git a/src/util.c b/src/util.c index 345fa0f5..469d7d2a 100644 --- a/src/util.c +++ b/src/util.c @@ -31,15 +31,16 @@ bool mg_random(void *buf, size_t len) { success = CryptGenRandom(hProv, len, p); } #else - // BCrypt is a "new generation" strong crypto API, so try it first - static BCRYPT_ALG_HANDLE hProv; - if (initialised == false && - BCryptOpenAlgorithmProvider(&hProv, BCRYPT_RNG_ALGORITHM, NULL, 0) == 0) { - initialised = true; - } - if (initialised == true) { - success = BCryptGenRandom(hProv, p, (ULONG) len, 0) == 0; + size_t i; + for (i = 0; i < len; i++) { + unsigned int rand_v; + if (rand_s(&rand_v) == 0) { + p[i] = (unsigned char)(rand_v & 255); + } else { + break; + } } + success = (i == len); #endif #elif MG_ARCH == MG_ARCH_UNIX