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
Release: 2024-12-04 06:59:13
Original
576 people have browsed it

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);
Copy after login

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
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template