Random numbers have many important uses in applied cryptography. Yet you can't compute true randomness arithmetically.
This project sources randomness from /dev/urandom
- this is a character special file in Linux (including Android) that provides access to a source of randomness generated by the Kernel. The randomness is sourced from environmental noise from device drivers and other sources - stored in an entropy pool.
Most userspace random number generators ultimately rely on /dev/urandom
. This project provides a convenient wrapper around /dev/urandom
to source random bytes.
Run make
in the project root directory.
The Makefile
expects a bin
directory. Running make
will build some example programmes:
g++ -W -Wall -std=c++17 -g -I. -o bin/main random.cpp main.cpp
g++ -W -Wall -std=c++17 -g -I. -o bin/diceroll random.cpp examples/diceroll.cpp
g++ -W -Wall -std=c++17 -g -I. -o bin/random-bytes random.cpp examples/random-bytes.cpp
g++ -W -Wall -std=c++17 -g -I. -o bin/code-usage random.cpp examples/code-usage.cpp
Initialise the Random
object with size_t n
.
Access a std::vector<unsigned char>
that contains n random bytes using getRandomBytes()
.
Member function printHex()
prints random bytes in zero-padded hexadecimal format.
Member function printInt()
prints random bytes in space-separated decimal format.
size_t n = 10;
Random r{n}; // Initialise with a size n
r.printInt(); // Prints n random bytes to stdout, decimal integers.
r.printHex(); // Prints n random bytes to stdout, hexadecimal format.
Initialise the Random
object with a suitable buffer to fill the buffer with random bytes.
std::vector<unsigned char> randVec(10);
Random r(randVec); // randVec now has 10 random bytes
Once the Random
object has been initialised, get it's randomBytes
member using getRandomBytes()
.
Returns a std::vector<unsigned char>
filled with random bytes.
std::vector<unsigned char> randBytes = r.getRandomBytes(); // Assign random bytes to a vector.
Call setRandomBytes()
to reset random bytes held by the object:
r.setRandomBytes(); // Bytes have been refreshed.
Next call to getRandomBytes()
return different values.
Passing a suitable buffer to getRandomBytes()
populates the buffer with random bytes.
Random r;
std::vector<unsigned char> buf;
r.getRandomBytes(buf);
// buf now contains random bytes
for (auto& el : buf)
std::cout << (int)el << " ";
std::cout << '\n';
// If initialised with a vector, fill vector with random values.
// -------------------------------------------------------------
std::vector<unsigned char> v(32);
Random r2{v};
std::cout << "printRandomBytes(v) =\n";
r2.printRandomBytes(v);
return 0;
}
unsigned char r = Random::getRandomByte();
std::cout << "r is a random byte, value " << (int)r << '\n';