pfok.h(3)

📦
version 2.2.0 · 2 versions
, in fedora 44

💅 pfok.h(3) — Library Functions Manual 💅

okay so bestie, this is the manual page for pfok.h, and it's literally giving Протоколы Проекта РД РБ (pfok). No cap, it's iconic. 💖

✨ NAME ✨

pfok.h — Протоколы Проекта РД РБ (pfok). 💅

🦋 SYNOPSIS 🦋

okay so here's the synopsis, periodt.

#include 'bee2/defs.h'

Классы

  • struct pfok_params — Долговременные параметры (long-term params, bestie 💅)
  • struct pfok_seed — Затравочные данные (seed data, slay)

Определения типов

  • typedef void(* pfok_on_q_i) (const word q[], const size_t n, size_t num) — Обработка нового числа q. (handling a new number q, iykyk)

Функции

  • err_t pfokSeedVal (const pfok_seed *seed) — Проверка затравочных параметров (checking seed params, no cap)
  • err_t pfokSeedAdj (pfok_seed *seed) — Настройка затравочных параметров (adjusting seed params)
  • err_t pfokParamsStd (pfok_params *params, pfok_seed *seed, const char *name) — Загрузка стандартных долговременных параметров (loading standard long-term params)
  • err_t pfokParamsGen (pfok_params *params, const pfok_seed *seed, pfok_on_q_i on_q) — Генерация долговременных параметров (generating long-term params)
  • err_t pfokParamsVal (const pfok_params *params) — Проверка долговременных параметров (checking long-term params)
  • err_t pfokKeypairGen (octet privkey[], octet pubkey[], const pfok_params *params, gen_i rng, void *rng_state) — Генерация пары ключей (generating a keypair)
  • err_t pfokPubkeyVal (const pfok_params *params, const octet pubkey[]) — Проверка открытого ключа (checking the public key)
  • err_t pfokPubkeyCalc (octet pubkey[], const pfok_params *params, const octet privkey[]) — Построение открытого ключа по личному (building the public key from the private one)
  • err_t pfokDH (octet sharekey[], const pfok_params *params, const octet privkey[], const octet pubkey[]) — Построение общего ключа протокола Диффи -- Хеллмана (building the shared key for the Diffie-Hellman protocol)
  • err_t pfokMTI (octet sharekey[], const pfok_params *params, const octet privkey[], const octet privkey1[], const octet pubkey[], const octet pubkey1[]) — Построение общего ключа протокола MTI. (building the shared key for the MTI protocol)

💖 Подробное описание 💖

okay so let's get into the deets, bestie.

Проект РД РБ (pfok): Общие положения

okay so the Проект РД РБ (pfok) protocols are implemented here. When we reference protocols, tables, or other objects, we mean the sections of the Project where those objects are defined. Also, data from СТБ 34.101.50 is used. ✨

Ожидается [ERR_BAD_INPUT]

Все входные указатели корректны. (All input pointers are correct, bestie. 🫶)

Регулярность

todo 💀

🌸 Типы 🌸

typedef void(* pfok_on_q_i) (const word q[], const size_t n, size_t num)

Обрабатывается построение очередного простого числа [n]q во время генерации параметра p = 2q + 1. Новое простое число получено в попытке с номером num (нумерация начиная с 1). (This handles the construction of the next prime number [n]q while generating the parameter p = 2q + 1. The new prime was obtained in the attempt with number num (numbering starts at 1).)

Прим.

При генерации долговременных параметров функция будет вызываться с возрастающим номером num до тех пор, пока p не окажется простым. (When generating long-term params, the function gets called with increasing num until p turns out prime.)

По окончании вычислений окончательное простое [n]q передается в функцию еще раз с нулевым num. В этом обращении можно выполнить завершающие служебные действия. (When the computation is done, the final prime [n]q is passed to the function one more time with num = 0. In that call you can do any final cleanup actions.)

Аргументы

  • q — простое число (prime number)
  • n — длина q в машинных словах (length of q in machine words)
  • num — номер попытки (attempt number)

🔥 Функции 🔥

okay so here are the functions, and they're all main character energy, periodt.

err_t pfokDH (octet sharekey[], const pfok_params *params, const octet privkey[], const octet pubkey[])

При долговременных параметрах params по личному ключу [O_OF_B(r)]privkey и открытому ключу [O_OF_B(l)]pubkey противоположной стороны строится общий ключ [O_OF_B(n)]sharekey. Общий ключ определяется как n битов числа pubkey^(privkey), что соответствует протоколу Диффи -- Хеллмана. (With long-term params params, using the private key [O_OF_B(r)]privkey and the other side's public key [O_OF_B(l)]pubkey, we build the shared key [O_OF_B(n)]sharekey. The shared key is defined as n bits of the number pubkey^(privkey), which matches the Diffie-Hellman protocol.)

Ожидается [ERR_BAD_PARAMS]

Параметры params корректны. (The params are correct.)

Ожидается [ERR_BAD_PUBKEY]

Открытый ключ pubkey корректен. (The public key pubkey is correct.)

Ожидается [ERR_BAD_PRIVKEY]

Личный ключ privkey корректен. (The private key privkey is correct.)

Возвращает

ERR_OK, если общий ключ успешно построен, и код ошибки в противном случае. (ERR_OK if the shared key was built successfully, and an error code otherwise.)

Прим.

Функция поддерживает протокол без аутентификации сторон (4.1) при следующих соглашениях: privkey = ua, pubkey = vb || privkey = ub, pubkey = va. (This function supports the unauthenticated protocol (4.1) with these conventions: ...)

Функция поддерживает односторонний протокол (4.3) при следующих соглашениях: privkey = ua, pubkey = yb || privkey = xb, pubkey = va. (It also supports the one-way protocol (4.3) with these conventions: ...)

Аргументы

  • sharekey — общий ключ (shared key)
  • params — долговременные параметры (long-term params)
  • privkey — личный ключ (private key)
  • pubkey — открытый ключ (другой стороны) (public key of the other side)

err_t pfokKeypairGen (octet privkey[], octet pubkey[], const pfok_params *params, gen_i rng, void *rng_state)

При долговременных параметрах params генерируются личный [O_OF_B(r)]privkey и открытый [O_OF_B(l)]pubkey ключи. При генерации используется генератор rng и его состояние rng_state. (With long-term params params, we generate the private [O_OF_B(r)]privkey and public [O_OF_B(l)]pubkey keys. The generator rng and its state rng_state are used for generation.)

Ожидается [ERR_BAD_PARAMS]

Параметры params корректны. (The params are correct.)

Ожидается [ERR_BAD_RNG]

Генератор rng (с состоянием rng_state) корректен. (The generator rng (with state rng_state) is correct.)

Ожидается

Используется криптографически стойкий генератор rng. (A cryptographically strong generator rng is used.)

Возвращает

ERR_OK, если ключи успешно сгенерированы, и код ошибки в противном случае. (ERR_OK if the keys were generated successfully, and an error code otherwise.)

Прим.

pubkey = g^(privkey).

Аргументы

  • privkey — личный ключ (private key)
  • pubkey — открытый ключ (public key)
  • params — долговременные параметры (long-term params)
  • rng — генератор случайных чисел (random number generator)
  • rng_state — состояние генератора (generator state)

err_t pfokMTI (octet sharekey[], const pfok_params *params, const octet privkey[], const octet privkey1[], const octet pubkey[], const octet pubkey1[])

При долговременных параметрах params по личному ключу [O_OF_B(r)]privkey, одноразовому личному ключу [O_OF_B(r)]privkey1, открытому ключу [O_OF_B(l)]pubkey противоположной стороны и одноразовому открытому ключу [O_OF_B(l)]pubkey противоположной стороны строится общий ключ [O_OF_B(n)]sharekey. Общий ключ определяется как n битов числа

pubkey1^(privkey) \xor pubkey^(privkey1).

что соответствует протоколу Диффи -- Хеллмана. (With long-term params params, using the private key [O_OF_B(r)]privkey, the one-time private key [O_OF_B(r)]privkey1, the other side's public key [O_OF_B(l)]pubkey, and the other side's one-time public key [O_OF_B(l)]pubkey1, we build the shared key [O_OF_B(n)]sharekey. The shared key is defined as n bits of the number ... which corresponds to the Diffie-Hellman protocol.)

Ожидается [ERR_BAD_PARAMS]

Параметры params корректны. (The params are correct.)

Ожидается [ERR_BAD_PUBKEY]

Открытый ключ pubkey корректен. (The public key pubkey is correct.)

Ожидается [ERR_BAD_PRIVKEY]

Личный ключ privkey корректен. (The private key privkey is correct.)

Возвращает

ERR_OK, если общий ключ успешно построен, и код ошибки в противном случае. (ERR_OK if the shared key was built successfully, and an error code otherwise.)

Прим.

Функция поддерживает протокол с аутентификацией сторон (4.2) при следующих соглашениях: privkey = xa, privkey1 = ua, pubkey = yb, pubkey1 = vb || privkey = xb, privkey1 = ub, pubkey = ya, pubkey1 = va.

Протокол 4.2 построен по схеме MTI (Matsumoto, Takashima, Imai), чем и объясняется название функции. (Protocol 4.2 is built on the MTI scheme (Matsumoto, Takashima, Imai), which explains the function's name.)

Аргументы

  • sharekey — общий ключ (shared key)
  • params — долговременные параметры (long-term params)
  • privkey — личный ключ (private key)
  • privkey1 — одноразовый личный ключ (one-time private key)
  • pubkey — открытый ключ (другой стороны) (public key of the other side)
  • pubkey1 — однораз. откр. ключ (др. стороны) (one-time public key of the other side)

err_t pfokParamsGen (pfok_params *params, const pfok_seed *seed, pfok_on_q_i on_q)

По затравочным параметрам seed генерируются долговременные параметры params. При построении очередного числа q, по которому определяется params->p, вызывается функция on_q. (From the seed params seed, the long-term params params are generated. When building the next number q, which determines params->p, the function on_q is called.)

Возвращает

ERR_OK, если параметры успешно сгенерированы, и код ошибки в противном случае. (ERR_OK if the params were generated successfully, and an error code otherwise.)

Прим.

Указатель on_q может быть нулевым и тогда построение q не обрабатывается. (The on_q pointer can be null, and then building q is not handled.)

Реализованы алгоритмы 5.2, 5.3. В качестве params->g выбираются последовательные числа 1, 2,... до тех пор, пока не встретится подходящее. (Algorithms 5.2 and 5.3 are implemented. For params->g, consecutive numbers 1, 2, ... are chosen until a suitable one is found.)

Аргументы

  • params — долговременные параметры (long-term params)
  • seed — затравочные параметры (seed params)
  • on_q — обработчик (handler)

err_t pfokParamsStd (pfok_params *params, pfok_seed *seed, const char *name)

В params загружаются стандартные долговременные параметры с именем name, а в seed -- затравочные параметры, на которых получены params. Указатель seed может быть нулевым, и в этом случае затравочные параметры не загружаются. Поддерживаются следующие имена: "1.2.112.0.2.0.1176.2.3.3.2", "1.2.112.0.2.0.1176.2.3.6.2", "1.2.112.0.2.0.1176.2.3.10.2". Это имена стандартных параметров, заданных в таблице В.3 СТБ 34.101.50. Дополнительно поддерживается имя "test" тестовых параметров первого уровня стойкости (l == 638). (Loads standard long-term params with the name name into params, and the seed params that produced params into seed. The seed pointer can be null, in which case seed params are not loaded. These names are supported: ... These are the names of standard params given in table В.3 of СТБ 34.101.50. Additionally, the name "test" is supported for test params of the first security level (l == 638).)


✨ part 2 loading, bestie, don't go anywhere 💅

Returns — ERR_OK if the params loaded successfully, otherwise an error code. Periodt. 💅

Arguments

  • params — standard params, the regular ones bestie
  • seed — seed params
  • name — name of the params

err_t pfokParamsVal (const pfok_params * params)

It checks that the long-term params params are correct. For the fields of params, these conditions get checked:

  • the dimensions l and r are consistent and match a defined security level;
  • n < l;
  • p is an l-bit prime number;
  • q = (p - 1) / 2 is prime;
  • g < p;
  • g has order p - 1 in the Montgomery group mod p.

Returns — ERR_OK if the params are correct, otherwise an error code.

Warnings — it does not check that p was built using algorithm 5.2. Not even a little. 🫠

Arguments

  • params — long-term params

err_t pfokPubkeyCalc (octet pubkey[], const pfok_params * params, const octet privkey[])

With long-term params params, using the private key [O_OF_B(r)]privkey, it builds the public key [O_OF_B(l)]pubkey. It’s giving key generation. ✨

Expected [ERR_BAD_PARAMS] — params params are correct. (So if they’re not, that error pops off.)

Expected [ERR_BAD_PRIVKEY] — private key privkey is correct. (Same energy: if it’s not, boom.)

Returns — ERR_OK if the public key was built successfully, otherwise an error code.

Note — pubkey = g^(privkey). Math is mathing. 🔥

Arguments

  • pubkey — public key
  • params — long-term params
  • privkey — private key

err_t pfokPubkeyVal (const pfok_params * params, const octet pubkey[])

With long-term params params, it checks the correctness of the public key [O_OF_B(l)]pubkey.

Expected [ERR_BAD_PARAMS] — params params are correct.

Returns — ERR_OK if the key is correct, otherwise an error code.

Arguments

  • params — long-term params
  • pubkey — the key being checked

err_t pfokSeedAdj (pfok_seed * seed)

In the seed structure, the unfilled (zero) params seed->zi and seed->li get default values. These values are determined with the help of seed->l like this:

  • zi[0] = 1,..., zi[30] = 31;
  • li[0] = l - 1, li[1] = li[0] / 2 + 1, ..., li[t] = li[t - 1] / 2 + 1 ∈ {17,..., 32}, 0, ...., 0.

Returns — ERR_OK if the resulting params are correct, otherwise an error code.

Arguments

  • seed — [in/out] seed params

err_t pfokSeedVal (const pfok_seed * seed)

It checks that the seed params seed are correct:

  • the dimension l matches a defined security level;
  • zi[i] ∈ {1, 2,..., 65256};
  • the array (chain) li starts with the number li[0] = l - 1 and ends with the number li[t] ∈ {17,...,32}, after which come zeros;
  • 5 * li[i + 1] / 4 + 4 < li[i] <= 2 * li[i + 1], 0 <= i < t.

Returns — ERR_OK if the params are correct, otherwise an error code.

Arguments

  • seed — seed params

Автор 💖

Automatically generated by Doxygen for the Bee2 Library (Библиотека Bee2) from the source text.


That’s the tea, bestie. This page is from Библиотека Bee2, dated Вс 25 Янв 2026 00:00:00, and it lives at pfok.h(3). Stay iconic. 💅✨

📦 where this page comes from