rng.h(3)
💖 rng.h(3) 💖
hi bestie, come CLOSE 🫶 this is rng.h, from page 3 of the Library Functions Manual, and it's literally the whole randomness situation — entropy sources and random number generators — which is lowkey the main character of the entire crypto library, because every key you will ever build walks out of this door. periodt. 🔥
fair warning: this page is LONG, so it comes in 2 parts and this is part 1. buckle up. 🎀
🌸 NAME 🌸
rng.h — entropy sources and random number generators 💫
✨ SYNOPSIS ✨
#include 'bee2/defs.h'
🧚 Functions
bool_t rngTestFIPS1 (const octet buf[2500])— the FIPS 140 sign test.bool_t rngTestFIPS2 (const octet buf[2500])— the FIPS 140 poker test.bool_t rngTestFIPS3 (const octet buf[2500])— the FIPS 140 runs test.bool_t rngTestFIPS4 (const octet buf[2500])— the FIPS 140 long-runs test.err_t rngESRead (size_t *read, void *buf, size_t count, const char *source)— reading data from an entropy source.err_t rngESTest (const char *source)— statistical testing of an entropy source.err_t rngESHealth ()— health check of the entropy sources.err_t rngESHealth2 ()— upgraded health check of the entropy sources.err_t rngCreate (read_i source, void *source_state)— creating the generator.bool_t rngIsValid ()— valid generator?void rngStepR (void *buf, size_t count, void *state)— generating random numbers.void rngStepR2 (void *buf, size_t count, void *state)— lightweight generation of random numbers.void rngRekey ()— rekeying the generator.void rngClose ()— closing the generator.
📖 ПОДРОБНОЕ ОПИСАНИЕ (the detailed description) 📖
🎲 Статистическое тестирование (statistical testing)
okay so the statistical tests of the FIPS 140-2 standard are implemented here. in these tests you process a sequence of binary symbols of length 20000 — which is 2500 bytes, bestie, the numbers line up, don't stress 💅
the significance level of the tests is p = 0.01. with that probability a truly random sequence will not pass the test. and it's a known thing that the FIPS tests are weakly dependent. so a truly random sequence will not pass a battery of n tests with probability 1 - (1 - p)^n ≈ n p. 😭 (yes the math is mathing — the more tests you stack, the more likely your perfect little random data gets clowned on. it's fine. it's expected. it's literally the design.)
Регулярность (regularity)
the data processed in the tests is not considered secret. like, at all. and these data must not be used to build keys. 🚫🔑
🌊 Источники энтропии (entropy sources)
a system can have several entropy sources, not just one. reading data from the sources is implemented through the read_i interface. the internal sources are supported by the rngESRead() function. 🦋
when a read request gets processed, the sources process their own observations while taking entropy estimates into account. if it's needed, the observations get compressed. and the result of processing the request is high-entropy data. heads up though: its volume may be less than what you asked for. 🙈
also, while a request is being processed, a source can just straight up fail, or the time it takes to take observations can turn out to be unacceptably large. in those cases too you'll get back less data than was requested. it's giving "we did our best, bestie". 😭
👑 Генератор случайных чисел (random number generator)
the output random numbers can be used to build keys and other critical objects. 🔥
the generator is the only one in the library. she's the moment. 💅
the generator can be used in multithreaded applications. slay.
when the generator is created, all available randomness sources get polled. the data from the sources is combined and hashed using the beltHash mechanism (see crypto/belt.h). that hash value is used as the key of the brngCTR mechanism (see crypto/brng.h). ✨
while the generator is functioning, successive calls to brngCTR are made. when those calls are being prepared, data from the available randomness sources can be used. this data is used as the input buffer of the brngCTRStepR() function.
data from the sources is used in the rngStepR() function and is not used in the rngStepR2() function. you can hit the first one from time to time (like, for instance, while a shared key is being agreed on before data transmission), and the second one regularly (during data transmission). 🎀
and with the rngRekey() function you can refresh the generator's key. after the key gets refreshed, the random numbers generated earlier become impossible to determine — even if no entropy sources were used while generating them, and even if the new key landed in the enemy's hands. ate. 👑
🛠 ФУНКЦИИ (functions) 🛠
void rngClose ()
the random number generator gets closed. bye bestie 💀
Предусловие (precondition): the generator is valid.
err_t rngCreate (read_i source, void * source_state)
a random number generator gets created. at creation time it uses the sources supported by the rngESRead() function, and also possibly an additional source source with the state source_state. 🌱
Ожидается [ERR_NOT_ENOUGH_ENTROPY] — taken all together, all the working sources give out at least 32 octets of random data.
Ожидается — the randomness sources give out high-entropy data.
Возвращает — a success flag.
Прим. (notes):
- with a zero
sourcethe additional source is not used. rngCreate()can be called multiple times. on repeated calls the accumulated entropy data is preserved, and the data obtained from the additional sourcesourceis added to it.- each source is asked for 32 octets of data, but it may give out less. data is not requested at all if the source is absent. 🙈
- a counter of calls to
rngCreate()is maintained. the counter is decremented by therngClose()function. when the counter reaches zero, the accumulated entropy data (including the cryptographic post-processing key) is destroyed. 💀
Аргументы (arguments):
source— the additional sourcesource_state— the state of the additional source
err_t rngESHealth ()
it's checked that among the standard entropy sources that withstand statistical testing there is one physical source or at least two different alternative ones. a vibe check on your entropy, basically. 🩺
Возвращает — ERR_OK if the check passed successfully, ERR_NOT_ENOUGH_ENTROPY if one working source is missing, and ERR_BAD_ENTROPY in all the other cases.
Прим. — the requirements being checked are the requirements of СТБ 34.101.27 level 1.
err_t rngESHealth2 ()
it's checked that among the entropy sources that withstand statistical testing there is one physical source. stricter. no shortcuts. 👑
Возвращает — ERR_OK if the check passed successfully, and ERR_BAD_ENTROPY otherwise.
Прим. — the requirements being checked are the requirements of СТБ 34.101.27 level 2 and above.
err_t rngESRead (size_t * read, void * buf, size_t count, const char * source)
data from the entropy source source gets written into the buffer [count]buf. the number of octets read is returned at the address read. the following sources are supported: 🦋
"trng"— a physical random number generator."trng2"— an additional physical random number generator."timer"— a high-precision timer. the observations are the differences between the timer readings before and after control is transferred to the operating system kernel."sys"— an operating system source.
Предусловие (preconditions):
- the buffer
bufis valid. - the pointer
readis valid.
Возвращает 💫
ERR_OK— если получено определённое число октетов (может быть меньше чемcount, может быть вообще ноль 🫶) и источник сохранил работоспособность;ERR_BAD_ENTROPY— если получено меньше чемcountоктетов и источник отказал 💀;- или другой код ошибки.
Прим. ✨
- Ситуация, когда сгенерировано меньше чем
countоктетов, ошибкой не считается. Ноу кэп. Такая ситуация может быть связана с ожиданием накопления наблюдений 👀. - Передавая
count == 0, можно проверить наличие источника. Вайб-чек для источника, лоукей. - Поддержан интерфейс
read_i.
Аргументы 🎀
read— число прочитанных октетовbuf— прочитанные данныеcount— длинаbufв октетахsource— источник
err_t rngESTest (const char * source)
Проводится статистическое тестирование источника энтропии source: к данным, полученным от источника, применяются тесты FIPS 🧪. Тестирование завершается успешно, если все тесты FIPS пройдены. То есть источник буквально сдаёт экзамен, и мы все держим за него кулачки 🫶.
Возвращает
ERR_OK— если тестирование прошло успешно;- код ошибки — в противном случае.
Аргументы
source— источник
bool_t rngIsValid ()
Проверяется корректность генератора случайных чисел. Просто спрашиваем у генератора: «ты ок?» и ждём честный ответ 💅.
Возвращает
- Признак корректности.
void rngRekey ()
Ключ генератора обновляется: в его качестве выступают генеририруемые случайные числа. При обновлении ключа данные от источников энтропии не используются. Генератор, так сказать, сам себя рекейит, мейн-кэрэктер энерджи 👑.
Предусловие
- Генератор корректен.
Ожидается
rngСreate() < rngRekey()*.
void rngStepR (void * buf, size_t count, void * state)
В буфер [count]buf записываются случайные октеты, построенные с помощью генератора случайных чисел. При формировании выходных октетов используются данные от источников случайности 🔥.
Предусловие
- Генератор корректен.
Ожидается
rngСreate() < rngStepR()*.
Прим.
- Поддержан интерфейс
gen_i(defs.h). - Состояние
stateне используется. Оно передается в функцию только для того, чтобы поддержать интерфейсgen_i. То есть это чисто для галочки, но мы всё равно его уважаем 🎀. - Запрашивается
countоктетов от источников. Будет возвращено меньше октетов только если все источники отказали. Все. Сразу. Абсолютный скеб-момент 💀.
Аргументы
buf— буферcount— размер буфера (в октетах)state— состояние (игнорируется)
void rngStepR2 (void * buf, size_t count, void * state)
В буфер [count]buf записываются случайные октеты, построенные с помощью генератора случайных чисел. При формировании выходных октетов данные от источников энтропии не используются. Сами справляемся, спасибо 🙈.
Предусловие
- Генератор корректен.
Ожидается
rngСreate() < rngStepR2()*.
Прим.
- Поддержан интерфейс
gen_i(defs.h). - Состояние
stateне используется. Оно передается в функцию только для того, чтобы поддержать интерфейсgen_i.
Аргументы
buf— буферcount— размер буфера (в октетах)state— состояние (игнорируется)
bool_t rngTestFIPS1 (const octet buf[2500])
К последовательности buf применяется тест знаков FIPS ⭐.
Предусловие
- Буфер
bufкорректен.
Возвращает
- Признак успешного прохождения теста.
Прим.
- Определяется величина
S— число единиц в последовательности. Тест пройден, если9725 < S < 10275.
Аргументы
buf— тестируемая последовательность
bool_t rngTestFIPS2 (const octet buf[2500])
К последовательности buf применяется покер-тест FIPS 🎲.
Предусловие
- Буфер
bufкорректен.
Возвращает
- Признак успешного прохождения теста.
Прим.
- Последовательность разбивается на 5000 тетрад. Тетрады интерпретируются как числа от 0 до 15. Определяется статистика
S = 16 \sum _{i=0}^15 S_i^2 - (5000)^2, гдеS_i— количество появлений числаiсреди тетрад. Тест пройден, если10800 < S < 230850.
Аргументы
buf— тестируемая последовательность
bool_t rngTestFIPS3 (const octet buf[2500])
К последовательности buf применяется тест серий FIPS 🌈.
Предусловие
- Буфер
bufкорректен.
Возвращает
- Признак успешного прохождения теста.
Прим.
- Определяются серии (максимальные последовательности повторяющихся соседних битов) различных длин. Тест пройден, если и для серий из нулей, и для серий из единиц выполняется:
S_1 ∈ [2315, 2685],S_2 ∈ [1114, 1386],S_3 ∈ [527, 723],S_4 ∈ [240, 384],S_5, S_6+ ∈ [103, 209]. ЗдесьS_i— количество серий длиныi = 1, 2, ...,S_6+ = S_6 + S_7 + .... - Бит с номером
i:wwTestBit((const word*)buf, i).
Аргументы
buf— тестируемая последовательность
bool_t rngTestFIPS4 (const octet buf[2500])
К последовательности buf применяется тест серий FIPS 💜.
Предусловие
- Буфер
bufкорректен.
Возвращает
- Признак успешного прохождения теста.
Прим.
- Тест пройден, если в последовательности отсутствуют серии длины 26 и больше.
- Бит с номером
i:wwTestBit((const word*)buf, i).
Аргументы
buf— тестируемая последовательность
Автор 👑
Автоматически создано Doxygen для Библиотека Bee2 из исходного текста. Да, страничку собрал робот, но вайб мы всё равно вытянули, фр фр 🤖💖
И вот мы у финиша, бести! 🦋 Это была страничка rng.h(3) из Библиотеки Bee2, собранная Вс 25 Янв 2026 00:00:00 — то есть библиотека нам это подарила буквально из будущего, айконик ⏰✨ Го читать остальные man-странички, там тоже имба, ноу кэп. Периодт 💅🌸
📦 where this page comes from
- fedora 44: bee2-devel 2.2.0-1.fc44 · GPL-3.0-only and GPL-3.0-or-later
- fedora 44: bee2-devel 2.2.0-1.fc44 · GPL-3.0-only and GPL-3.0-or-later
- 💖 girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms