Team LiB
Previous Section Next Section

Interfaces to Output Entropy

The kernel exports one interface for obtaining random data from within the kernel:

void get_random_bytes(void *buf, int nbytes)

This function stores nbytes worth of random data in the buffer pointed to by buf. The function returns the values, whether or not the entropy estimate is zero. This is less of a concern to the kernel than user-space cryptography applications. The random data is suitable for a handful of kernel tasks, most notably in networking, where the random data seeds the initial TCP sequence number.

Kernel code can do the following to receive a word-size helping of randomness:

unsigned long rand;

get_random_bytes(&rand, sizeof (unsigned long));

For user-space processes, the kernel provides two character devices, /dev/random and /dev/urandom, for obtaining entropy. The first, /dev/random, is more suitable when very strong random numbers are desired, as in high-security cryptographic applications. It returns only up to the maximum number of bits of random data noted by the entropy estimate. When the entropy estimate reaches zero, /dev/random blocks and does not return the remaining data until the entropy estimate is sufficiently positive. Conversely, the device /dev/urandom does not have this feature and is generally just as secure. Both devices return numbers from the same pool.

Reading from either file is simple. Here is an example of a user-space function that an application can use to extract a word of entropy:

unsigned long get_random(void)
{
        unsigned long seed;
        int fd;

        fd = open("/dev/urandom", O_RDONLY);
        if (fd == -1) {
                perror("open");
                return 0;
        }
        if (read(fd, &seed, sizeof (seed)) < 0) {
                perror("read");
                seed = 0;
        }
        if (close(fd))
                perror("close");

        return seed;
}

Alternatively, you can easily read bytes bytes into the file file by using the dd(1) program:

dd if=/dev/urandom of=file count=1 bs=bytes

    Team LiB
    Previous Section Next Section