Home >Backend Development >C++ >How Can I Generate Thoroughly Random Seeds for mt19937 in C ?

How Can I Generate Thoroughly Random Seeds for mt19937 in C ?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-04 06:59:13508browse

How Can I Generate Thoroughly Random Seeds for mt19937 in C  ?

Thorough Random Seed Generation for mt19937 in C

Problem:

Recent answers often suggest using with std::random_device to seed the mt19937 PRNG, which is flawed as it doesn't provide sufficient randomness, can be predictable, and may use a PRNG with fixed seed.

Portable and Thorough Seeding:

A portable and thorough approach to seeding mt19937 involves using a CSPRNG, such as:

  • Windows: sysrandom utilizing CryptGenRandom
  • Unix-Like: sysrandom utilizing /dev/urandom (or getrandom if available on Linux 3.17 or higher)
  • OpenBSD: sysrandom utilizing getentropy

Code Example:

#include <cstdint>
#include <cstdlib>
#include <fstream>

size_t sysrandom(void* dst, size_t dstlen);

std::uint_least32_t seed;
sysrandom(&seed, sizeof(seed));
std::mt19937 gen(seed);

Linux Specialization with getrandom:

#if defined(HAVE_GETRANDOM)
size_t sysrandom(void* dst, size_t dstlen) {
  int bytes = syscall(SYS_getrandom, dst, dstlen, 0);
  if (bytes != dstlen) {
    throw std::runtime_error("Unable to read N bytes from CSPRNG.");
  }
  return dstlen;
}
#endif

OpenBSD Special Case:

#if defined(HAVE_GETENTROPY)
size_t sysrandom(void* dst, size_t dstlen) {
  int bytes = getentropy(dst, dstlen);
  if (bytes != dstlen) {
    throw std::runtime_error("Unable to read N bytes from CSPRNG.");
  }
  return dstlen;
}
#endif

Other Thoughts:

  • Use an unbuffered read/write approach for cryptographically secure random bytes.
  • Specialized functions (e.g., for Linux or OpenBSD) can be added for improved efficiency.

The above is the detailed content of How Can I Generate Thoroughly Random Seeds for mt19937 in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn