Cryptographically Secure Random number on Windows without using CryptoAPI

Historically, we always told developers not to use functions such as rand to generate keys, nonces and passwords, rather they should use functions like CryptGenRandom, which creates cryptographically secure random numbers. The problem with CryptGenRandom is you need to pull in CryptoAPI (CryptAcquireContext and such) which is fine if you're using other crypto functions.

On a default Windows XP and later install, CryptGenRandom calls into a function named ADVAPI32!RtlGenRandom, which does not require you load all the CryptAPI stuff. In fact, the new Whidbey CRT function, rand_s calls RtlGenRandom.

The following snippet shows how to call the function.

HMODULE hLib=LoadLibrary("ADVAPI32.DLL");
if (hLib) {
BOOLEAN (APIENTRY *pfn)(void*, ULONG) =
      (BOOLEAN (APIENTRY *)(void*,ULONG))GetProcAddress(hLib,"SystemFunction036");
if (pfn) {
char buff[32];
ULONG ulCbBuff = sizeof(buff);
if(pfn(buff,ulCbBuff)) {

   // use buff full of random goop

}
}

 FreeLibrary(hLib);
}

The good news is you can get good random numbers, without the memory overhead of pulling in all of CryptoAPI!

RtlGenRandom is documented at https://msdn.microsoft.com/library/en-us/seccrypto/security/rtlgenrandom.asp.