randombytes - fill a buffer with random data
#include <randombytes.h> unsigned char x[xbytes]; randombytes(x,xbytes);
x[xbytes-1] to random bytes of
Randomness APIs vary in three major ways.
randombytes is designed in
each way to simplify callers:
randombytesautomatically generates separate randomness for any number of bytes in any number of calls in any number of threads in any number of programs. For comparison, some randomness APIs (e.g.,
random) recycle randomness from one program to another unless the program does extra work to set a separate "seed", and can recycle randomness across multiple threads unless the program does further work.
randombytesaims for the stringent goal of ensuring that no feasible computation will ever be able to tell the difference between the output bytes and true randomness. The caller can treat each returned byte as the result of 8 fresh coin flips. For comparison, some randomness APIs (e.g.,
random) do not aim for this goal and do not view detectable patterns as a bug, as long as most applications do not notice the patterns.
randombytesalways succeeds. Any necessary resources (e.g., opening a file descriptor for
/dev/urandom, on systems that need this) are allocated at program startup, rather than being deferred until the first
randombytescall; also, dynamic failure cases such as EINTR are handled inside
randombytes. For comparison, some randomness APIs (e.g.,
RAND_bytes) can return error codes to be handled by the caller.
There are some programs that try to close all file descriptors. These
programs must limit their library use to libraries that promise not to
keep file descriptors open. In particular, these programs must not use
randombytes (which keeps a file descriptor open on some systems) or
other libraries calling
-lrandombytes is a frontend symbolic link to either
-lrandombytes-openssl as a backend library.
To simplify system-wide replacement of the backend library, typical
applications should dynamically link to
-lrandombytes rather than to
Applications that link statically to
-lrandombytes also need
randombytes is a macro, where the function actually linked
randombytes API was introduced in 2008 as part of the
benchmarking framework for cryptographic software.
Similar previous APIs include
RAND_bytes was allowed to return failures and
using the broken RC4 stream cipher.
getrandom(2), getentropy(2), rand(3), random(3), arc4random(3), urandom(4)
Version: This is version 2023.01.16 of the "API" web page.