Generating Random Numbers

Cryptographically strong pseudorandom numbers are required for a number of encryption algorithms. Because these pseudorandom numbers are generated by a computer algorithm, they are not truly random. However, the algorithm is not discernible from the sequence.

The way you generate random numbers depends on whether you are writing code for OS X or iOS.

Generating Random Numbers in OS X

In OS X, you can get cryptographically secure pseudorandom numbers by reading bytes from the /dev/random device file. Each byte from this file is a cryptographically random value from 0-255. By concatenating these bytes, you can generate a random number of an arbitrary size.

For example, if you need a random 64-bit integer value, you could write code like this:

FILE *fp = fopen("/dev/random", "r");
if (!fp) {
uint64_t value = 0;
int i;
for (i=0; i<sizeof(value); i++) {
    uint8_t c = fgetc(fp);
    value |= (c << (8 * i));

The task of converting such a value to an evenly distributed value in a given range is left as an exercise for the reader.

Generating Random Numbers in iOS

In iOS, you can use Randomization Services to generate these numbers. Randomization Services, in turn, calls a random number generator in the Core OS layer. For more information, read Randomization Services Reference.