How to Thoroughly Seed the MT19937 PRNG in C
Typically, std::random_device is used to generate random numbers, as seen in the following code:
std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> dis(0, 5); dis(gen);
However, this method is flawed because:
A more reliable approach is to use a CSPRNG, such as CryptGenRandom on Windows or /dev/urandom on Unix-like systems, to generate high-quality random bytes to seed the PRNG. For example:
#include <bit> #include <iostream> #include <string> size_t sysrandom(void* dst, size_t dstlen) { std::ifstream stream("/dev/urandom", std::ios_base::binary | std::ios_base::in); stream.read((char*)dst, dstlen); return dstlen; } int main() { std::uint_least32_t seed; sysrandom(&seed, sizeof(seed)); std::mt19937 gen(seed); // Your code to use the generator here... return 0; }
This code uses /dev/urandom as the CSPRNG and seeds the PRNG using a 32-bit value, which should be increased for better security. This approach is portable, well-tested, and easy to use, providing a solid foundation for generating random numbers in C .
The above is the detailed content of How Can I Properly Seed the MT19937 PRNG in C for Secure Random Number Generation?. For more information, please follow other related articles on the PHP Chinese website!