skalibs: the random library interface
Keywords: skalibs library random librandom random.h

libskarnet
skalibs
Software
skarnet.org

# The `random` library interface

`librandom` is a small library designed to provide an interface to some reasonable-quality pseudorandom number generation. `librandom` uses arc4random when available, or getrandom - else it defaults to `/dev/urandom` and a a SURF PRNG.

## Compiling

- Use `#include <skalibs/random.h>`

## Programming

You should refer to the `skalibs/random.h` header for the exact function prototypes.

### Basic functions

      unsigned char c ;
      uint32_t max ;
      uint32_t n ;
      size_t b ;
      char data[at least b] ;
      int r ;

      r = random_init() ;
      c = random_char() ;
      n = random_uint32(max) ;
      random_string(data, b) ;
      random_finish() ;

`random_init()` must be called before any other function in the random library. It returns 0 (and sets errno) on failure, and nonzero on success.

It is recommended that you let the library perform cleanups after you are done using it, by calling `random_finish()` - unless your process exits right away.

- `random_char()` returns a random character.
- `random_uint32(max)` returns a random integer between 0 and max-1.
- `random_string(data, b)` fills b bytes in data (which must be preallocated) with random data.

### Advanced functions

`void random_unsort (char *s, unsigned int n, unsigned int chunksize)`
Shuffles the array s (of size at least n*chunksize) by performing a random permutation of the n blocks of chunksize bytes. Bytes are not permuted inside chunks.

`void random_name (char *s, size_t n)`
Writes n random readable ASCII characters into s: letters, numbers, hyphens or underscores. Does not terminate with a null character.

`int random_sauniquename (stralloc *sa, unsigned int n)`
Appends a (non-null-terminated) unique, unpredictable ASCII name to the stralloc *sa. That name includes n randomly generated ASCII characters.

## Notes

- The `random` library is a thin wrapper around the best available random generator provided by the underlying system. By decreasing order of preference, it will use the following implementations if available:
  - arc4random()
  - getrandom()
  - `/dev/urandom`
  - a basic SURF pseudo-random generator
- The `random_init()` function tries to automatically add some reasonably random data to the underlying random generator's entropy pool. However, that pseudorandom data is not 100% unpredictable, so it will not replace proper seeding of the random generator at boot time.