Skip to content

nqrand(3)

nqrand, nqsetrng — random bytes from the operating system or the caller's source

libnoqtis, -lnoqtis

#include <noqtis.h>

int
nqrand(uint8_t *buf, size_t len);

typedef int (*nqrngfn)(uint8_t *buf, size_t len, void *user);

int
nqsetrng(nqrngfn fn, void *user);

() fills buf with len bytes from the operating system's cryptographically secure random source: getrandom(2) on Linux, arc4random_buf(3) on macOS and the BSDs, () on Windows, and getentropy(3) under WebAssembly (WebCrypto () with emscripten, WASI () with wasi-sdk). Large requests are made in chunks. There is no fallback source and no user-space generator: when the operating system's source fails, so does nqrand().

Every function of noqtis(3) that needs randomness (key generation, hedged signing, encapsulation, mask shares) takes it from here.

() makes nqrand() take its bytes from fn instead, called with user; fn returns 0 when it filled buf and anything else when it failed, and nqrand() then fails with NQERNG. A NULL fn gives the operating system's source back. The setting is global and not synchronised: set it once, before any thread uses the library. The source must be a cryptographically secure one (a hardware random number generator, a DRBG seeded from one); the library does not test it.

In the freestanding build (-DNQFREE=ON), for firmware and kernels without an operating system's source, () fails with NQERNG until nqsetrng() has given it one.

buf holds len random bytes. A len of 0 succeeds and writes nothing.
[NQEARG]
buf is NULL and len is not 0.
[NQERNG]
The operating system's source failed, or the caller's source did, or (in the freestanding build) no source was set.

nqsetrng() returns NQOK.

uint8_t key[32];
if (nqrand(key, sizeof key) != NQOK)
  abort();
/* ... use the key ... */
nqwipe(key, sizeof key);

noqtis(3), nqwipe(3)