Use modern function for getting random numbers on Windows

The previous `RtlGenRandom()` just redirects to `ProcessPrng()` according to "The Windows 10
random number generation infrastructure" whitepaper from MS.

`ProcessPrng()` is also the de facto PRNG for Rust lang:
aa13fa5882/src/windows.rs (L3C1-L22C81)
And for golang:
https://go-review.googlesource.com/c/go/+/536235
This commit is contained in:
Chocobo1 2024-09-12 16:56:15 +08:00
commit 3058158b69
No known key found for this signature in database
GPG key ID: 210D9C873253A68C

View file

@ -33,9 +33,10 @@
#include <QtLogging> #include <QtLogging>
#include <QtSystemDetection> #include <QtSystemDetection>
#ifdef Q_OS_WIN #if defined(Q_OS_WIN)
#include <windows.h> #include <windows.h>
#include <ntsecapi.h> #include "base/global.h"
#include "base/utils/os.h"
#elif defined(Q_OS_LINUX) #elif defined(Q_OS_LINUX)
#include <cerrno> #include <cerrno>
#include <cstring> #include <cstring>
@ -46,17 +47,9 @@
#include <cstring> #include <cstring>
#endif #endif
#include <QString>
#include "base/global.h"
#ifdef Q_OS_WIN
#include "base/utils/os.h"
#endif
namespace namespace
{ {
#ifdef Q_OS_WIN #if defined(Q_OS_WIN)
class RandomLayer class RandomLayer
{ {
// need to satisfy UniformRandomBitGenerator requirements // need to satisfy UniformRandomBitGenerator requirements
@ -64,10 +57,10 @@ namespace
using result_type = uint32_t; using result_type = uint32_t;
RandomLayer() RandomLayer()
: m_rtlGenRandom {Utils::OS::loadWinAPI<PRTLGENRANDOM>(u"Advapi32.dll"_s, "SystemFunction036")} : m_processPrng {Utils::OS::loadWinAPI<PPROCESSPRNG>(u"BCryptPrimitives.dll"_s, "ProcessPrng")}
{ {
if (!m_rtlGenRandom) if (!m_processPrng)
qFatal("Failed to load RtlGenRandom()"); qFatal("Failed to load ProcessPrng().");
} }
static constexpr result_type min() static constexpr result_type min()
@ -83,16 +76,16 @@ namespace
result_type operator()() result_type operator()()
{ {
result_type buf = 0; result_type buf = 0;
const bool result = m_rtlGenRandom(&buf, sizeof(buf)); const bool result = m_processPrng(reinterpret_cast<PBYTE>(&buf), sizeof(buf));
if (!result) if (!result)
qFatal("RtlGenRandom() failed"); qFatal("ProcessPrng() failed.");
return buf; return buf;
} }
private: private:
using PRTLGENRANDOM = BOOLEAN (WINAPI *)(PVOID, ULONG); using PPROCESSPRNG = BOOL (WINAPI *)(PBYTE, SIZE_T);
const PRTLGENRANDOM m_rtlGenRandom; const PPROCESSPRNG m_processPrng;
}; };
#elif defined(Q_OS_LINUX) #elif defined(Q_OS_LINUX)
class RandomLayer class RandomLayer