expand.h

Seed expansion: AES-128 in counter mode, filtered to values below a bound.

The sampler for bulk public randomness, such as a seeded MLWE mask. The sequence is a file-format commitment: stored seeds are re-expanded through it, so it never changes. Under a 16-byte key:

keystream block (j, t) = AES-128_key(LE64(j) || LE64(t))
w = 4 if bound <= 2^32 else 8;  m = the smallest 2^k - 1 >= bound - 1
value i = the first, over attempts t = 0, 1, ..., of
          (the w-byte little-endian word at byte i*w of attempt t's
           keystream) & m  that is below bound
Values are exactly uniform in [0, bound), value i depends on i alone, and every engine computes the same sequence. The key is public: the AES here is not constant time on the portable engine.

Note

Thread-safe; no state.

Functions

void expand_key(uint8_t key[16], const char *context, const uint8_t *seed, uint64_t seed_len, const uint64_t *label, uint64_t label_len)

Derives the key a seed expands under: the first 16 bytes of BLAKE3 in derive-key mode with context, over seed followed by each word of label as 8 little-endian bytes.

Parameters:
  • key – [out] Receives the key.

  • context – [in] A fixed string literal per use.

  • seed – [in] Any length.

  • seed_len – [in] Bytes of seed.

  • label – [in] Separates the streams drawn from one seed.

  • label_len – [in] Words of label.

void expand_below(uint64_t *out, uint64_t count, uint64_t start, uint64_t bound, const uint8_t key[16])

Writes values [start, start + count) of the sequence key defines, as 64-bit words.

Parameters:
  • out – [out] Receives count values.

  • count – [in] Values.

  • start – [in] Index of the first.

  • bound – [in] Values are below it; at least 1.

  • key – [in] From expand_key().

Pre:

bound is at least 1.

void expand_below32(uint32_t *out, uint64_t count, uint64_t start, uint64_t bound, const uint8_t key[16])

The same values as 32-bit words, for a bound up to 2^32.

Parameters:
  • out – [out] Receives count values.

  • count – [in] Values.

  • start – [in] Index of the first.

  • bound – [in] Values are below it; in [1, 2^32].

  • key – [in] From expand_key().

Pre:

bound is in [1, 2^32].

void expand_aes128_ctr(uint8_t *out, uint64_t count, uint64_t first, uint64_t attempt, const uint8_t key[16])

Writes keystream blocks first .. first + count - 1 of attempt attempt under key, 16 bytes each: the blocks the sequence above is read from.

Parameters:
  • out – [out] Receives 16 * count bytes.

  • count – [in] Blocks.

  • first – [in] Index of the first block.

  • attempt – [in] The attempt, t above.

  • key – [in] Any 16 bytes.