Advertisement
Guest User

Cross-platform PRNG seed

a guest
Jul 27th, 2011
288
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.93 KB | None | 0 0
  1. seed_type prng_seed = 0;  // suitable integral type
  2. MyRNG     prng;           // something from <random>
  3.  
  4. void initPRNG()
  5. {
  6.   bool seedsuccess = false;
  7.  
  8. #ifdef WIN32
  9.   HCRYPTPROV hCryptProv;
  10.   BYTE* pbData = reinterpret_cast<BYTE*>(&prng_seed);
  11.  
  12.   if (CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, 0))
  13.   {
  14.     if (CryptGenRandom(hCryptProv, sizeof(prng_seed), pbData))
  15.     {
  16.       seedsuccess = true;
  17.     }
  18.     CryptReleaseContext(hCryptProv, 0);
  19.   }
  20. #else
  21.   std::ifstream urandom("/dev/urandom");
  22.   if (urandom)
  23.   {
  24.     urandom.read(reinterpret_cast<char*>(&prng_seed), sizeof(prng_seed));
  25.     seedsuccess = true;
  26.   }
  27. #endif
  28.  
  29.   if (!seedsuccess)
  30.   {
  31.     prng_seed = std::time(NULL);
  32.   }
  33.  
  34.   //std::cout << "Seeding the PRNG with: 0x" << std::hex << std::uppercase << std::setfill('0')
  35.   //          << std::setw(2 * sizeof(MyRNG::result_type)) << prng_seed << std::endl;
  36.  
  37.   prng.seed(prng_seed);
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement