Search code examples
c++randomrandom-seed

Get different random bytes each run


I'd like to generate a bunch of random bytes in C++. For this, I use

#include <climits>
#include <functional>
#include <random>
#include <vector>
#include <iostream>

using random_bytes_engine = std::independent_bits_engine<
    std::default_random_engine, CHAR_BIT, unsigned char>;

int main()
{
    random_bytes_engine rbe;
    std::vector<unsigned char> data(10);
    std::generate(begin(data), end(data), std::ref(rbe));

    for(int b: data) {
      std::cout << b << ", ";
    }
    std::cout << std::endl;
}
166, 240, 216, 41, 129, 199, 215, 253, 66, 76,

Nice. Now, I'd like to make sure that I get different values each time I run the program, i.e., I'd like to seed the independent_bits_engine from somewhere.

Any hints? The solution must be cross-platform. (Portable solutions other than independent_bits_engine would also work.)


Solution

  • There is an example in the documentation, but it is slightly hidden as it is mentioned for the constructor, not for the main class:

    std::random_device rd;
    std::independent_bits_engine<std::mt19937, /*bits*/ 3, unsigned long> e3(rd()); // seeded with rd()
    

    Where the instance of random_device represents the system specific random number generator, as specified here. Of course, you'd still have to verify that there is such a random number generator present, but I guess this is about as random as it gets without using system specific functionality. A discussion on the security of the randomness generated can be found here.