Skip to content

Random numbers

Ulrich Koschella edited this page Aug 11, 2023 · 24 revisions

Generating random data

Example

uint32_t r_uint32 = hydro_random_u32();

uint32_t r_in_0_to_99 = hydro_random_uniform(100);

uint8_t buf[32];
hydro_random_buf(buf, sizeof buf);

uint8_t seed[hydro_random_SEEDBYTES] = { 0 };
hydro_random_buf_deterministic(buf, sizeof buf, seed);

Purpose

Generate unpredictable data, suitable for creating secret keys.

32-bit random numbers

uint32_t hydro_random_u32(void);

The hydro_random_u32() function returns an unpredictable value between 0 and 0xffffffff (included).

Random numbers within an arbitrary interval

uint32_t hydro_random_uniform(const uint32_t upper_bound);

The hydro_random_uniform() function returns an unpredictable value between 0 and upper_bound (excluded). Unlike hydro_random_u32() % upper_bound, it does its best to guarantee a uniform distribution of the possible output values even when upper_bound is not a power of 2.

Generating an arbitrary long random sequence

void hydro_random_buf(void *buf, size_t len);

The hydro_random_buf() function fills size bytes starting at buf with an unpredictable sequence of bytes, derived from a secret seed automatically generated by hydro_init().

Deterministic random numbers

void hydro_random_buf_deterministic(
    void *buf, size_t len, const uint8_t seed[hydro_random_SEEDBYTES]);

The hydro_random_buf_deterministic() function stores len bytes into buf indistinguishable from random bytes without knowing seed. For a given seed, this function will always output the same sequence. This function is mainly useful for writing tests.

Ratcheting

void hydro_random_ratchet(void);

The hydro_random_ratchet() function erases part of the state and replaces the secret key, making it impossible to recover the previous states in case the current one ever gets exposed due to a vulnerability.

Reseeding

void hydro_random_reseed(void);

The hydro_random_reseed() function must be called after a fork() call.

Constants

#define hydro_random_SEEDBYTES 32

Note

If this is used in an application inside a VM, and the VM is snapshotted and restored, then the above functions will produce the same output.