Random number generation (RNG) is the process of randomly generating numbers in a certain range. RNG is widespread it is for cryptography and computer security, meaning that secure and safe ways to generate numbers is important.

In software

Most random number generators use seeds to determine which numbers should be pseudo-randomly output. These seeds initialise the generator. While the seeds may not necessarily be random, the output of the generator will be pseudo random and follow a probability distribution.

Secure generation

In C++, robust RNG can be done as follows:

#include <random>
 
double rng_double(double lower, double upper) {
	std::random_device rd;
	std::mt19937 gen(rd());
	std::uniform_real_distribution<double> dis(lower, upper);
	return dis(gen);
}

Line-by-line, this:

  • Creates a random device to seed the random number generator.
  • Creates a Mersenne Twister engine that’s seeded with the random-device.
  • Creates a uniform real distribution between the upper and lower limits.
  • Returns a random number in the distribution.

Time-based generation

A way to get moderately robust RNG is with time-based generation. This is not cryptographically secure, so it’s best not to use this unless security isn’t critically important.

In hardware

In some embedded hardware systems, it’s possible to generate a pseudo random number based assuming a fast enough clock and user-input. We can use a digital counter circuit and take the value of the counter at the positive edge of the user input.