Succinct, Portable, and Thorough Seeding of Mt19937 PRNG in C
Despite the shortcomings of using std::random_device and time(NULL) for seeding, it's possible to achieve a robust and portable solution:
CSPRNG-Based Seeding
To avoid the limitations of std::random_device, we can utilize a CSPRNG such as:
Minimal Seeding Function:
The following cross-platform function provides a minimal wrapper around various OS-specific CSPRNGs:
size_t sysrandom(void* dst, size_t dstlen) { #ifdef _WIN32 // Windows CSPRNG implementation #elif defined(__linux__) // Linux CSPRNG implementation #else // POSIX CSPRNG implementation #endif }
Efficient Seeding:
With sysrandom available, seeding the mt19937 PRNG becomes:
std::uint_least32_t seed; sysrandom(&seed, sizeof(seed)); std::mt19937 gen(seed);
Additional Notes:
The above is the detailed content of How Can I Securely Seed the Mt19937 PRNG in C Across Different Platforms?. For more information, please follow other related articles on the PHP Chinese website!