mlkem.c 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091
  1. /*
  2. * Implementation of ML-KEM, previously known as 'Crystals: Kyber'.
  3. */
  4. #include <stdio.h>
  5. #include <stdarg.h>
  6. #include <stdlib.h>
  7. #include <assert.h>
  8. #include "putty.h"
  9. #include "ssh.h"
  10. #include "mlkem.h"
  11. #include "smallmoduli.h"
  12. /* ----------------------------------------------------------------------
  13. * General definitions.
  14. */
  15. /*
  16. * Arithmetic in this system works mod 3329, which is prime, and
  17. * congruent to 1 mod 256 (in fact it's 13*256 + 1), meaning that
  18. * 256th roots of unity exist.
  19. */
  20. #define Q 3329
  21. /*
  22. * Parameter structure describing a particular instance of ML-KEM.
  23. */
  24. struct mlkem_params {
  25. int k; /* dimensions of the matrices used */
  26. int eta_1, eta_2; /* parameters for mlkem_matrix_poly_cbd calls */
  27. int d_u, d_v; /* bit counts to use in lossy compressed encoding */
  28. };
  29. /*
  30. * Specific parameter sets.
  31. */
  32. const mlkem_params mlkem_params_512 = {
  33. .k = 2, .eta_1 = 3, .eta_2 = 2, .d_u = 10, .d_v = 4,
  34. };
  35. const mlkem_params mlkem_params_768 = {
  36. .k = 3, .eta_1 = 2, .eta_2 = 2, .d_u = 10, .d_v = 4,
  37. };
  38. const mlkem_params mlkem_params_1024 = {
  39. .k = 4, .eta_1 = 2, .eta_2 = 2, .d_u = 11, .d_v = 5,
  40. };
  41. #define KMAX 4
  42. /* ----------------------------------------------------------------------
  43. * Number-theoretic transform on ring elements.
  44. *
  45. * The ring R used by ML-KEM is (Z/qZ)[X] / <X^256+1> (where q=3329 as
  46. * above). If the quotient polynomial were X^256-1 then it would split
  47. * into 256 linear factors, so that R could be expressed as the direct
  48. * sum of 256 rings (Z/qZ)[X] / <X-zeta^i> (where zeta is some fixed
  49. * primitive 256th root of unity mod q), each isomorphic to Z/qZ
  50. * itself. But X^256+1 only splits into 128 _quadratic_ factors, and
  51. * hence we can only decompose R as the direct sum of rings of the
  52. * form (Z/qZ)[X] / <X^2-zeta^j> for odd j, each a quadratic extension
  53. * of Z/qZ, and all mutually nonisomorphic. This means the NTT runs
  54. * one pass fewer than you'd "normally" expect, and also, multiplying
  55. * two elements of R in their NTT representation is not quite as
  56. * trivial as it would normally be - within each component ring of the
  57. * direct sum you have to do the multiplication slightly differently
  58. * depending on the power of zeta in its quotient polynomial.
  59. *
  60. * We take zeta=17 to be the canonical primitive 256th root of unity
  61. * for NTT purposes.
  62. */
  63. /*
  64. * First 128 powers of zeta, reordered by bit-reversing the 7-bit
  65. * index. That is, the nth element of this array contains
  66. * zeta^(bitrev7(n)). Used by the NTT itself.
  67. */
  68. static const uint16_t powers_reversed_order[128] = {
  69. 1, 1729, 2580, 3289, 2642, 630, 1897, 848, 1062, 1919, 193, 797, 2786,
  70. 3260, 569, 1746, 296, 2447, 1339, 1476, 3046, 56, 2240, 1333, 1426, 2094,
  71. 535, 2882, 2393, 2879, 1974, 821, 289, 331, 3253, 1756, 1197, 2304, 2277,
  72. 2055, 650, 1977, 2513, 632, 2865, 33, 1320, 1915, 2319, 1435, 807, 452,
  73. 1438, 2868, 1534, 2402, 2647, 2617, 1481, 648, 2474, 3110, 1227, 910, 17,
  74. 2761, 583, 2649, 1637, 723, 2288, 1100, 1409, 2662, 3281, 233, 756, 2156,
  75. 3015, 3050, 1703, 1651, 2789, 1789, 1847, 952, 1461, 2687, 939, 2308, 2437,
  76. 2388, 733, 2337, 268, 641, 1584, 2298, 2037, 3220, 375, 2549, 2090, 1645,
  77. 1063, 319, 2773, 757, 2099, 561, 2466, 2594, 2804, 1092, 403, 1026, 1143,
  78. 2150, 2775, 886, 1722, 1212, 1874, 1029, 2110, 2935, 885, 2154,
  79. };
  80. /*
  81. * First 128 _odd_ powers of zeta: the nth element is
  82. * zeta^(2*bitrev7(n)+1). Each of these is used for multiplication in
  83. * one of the 128 quadratic-extension rings in the NTT decomposition.
  84. */
  85. static const uint16_t powers_odd_reversed_order[128] = {
  86. 17, 3312, 2761, 568, 583, 2746, 2649, 680, 1637, 1692, 723, 2606, 2288,
  87. 1041, 1100, 2229, 1409, 1920, 2662, 667, 3281, 48, 233, 3096, 756, 2573,
  88. 2156, 1173, 3015, 314, 3050, 279, 1703, 1626, 1651, 1678, 2789, 540, 1789,
  89. 1540, 1847, 1482, 952, 2377, 1461, 1868, 2687, 642, 939, 2390, 2308, 1021,
  90. 2437, 892, 2388, 941, 733, 2596, 2337, 992, 268, 3061, 641, 2688, 1584,
  91. 1745, 2298, 1031, 2037, 1292, 3220, 109, 375, 2954, 2549, 780, 2090, 1239,
  92. 1645, 1684, 1063, 2266, 319, 3010, 2773, 556, 757, 2572, 2099, 1230, 561,
  93. 2768, 2466, 863, 2594, 735, 2804, 525, 1092, 2237, 403, 2926, 1026, 2303,
  94. 1143, 2186, 2150, 1179, 2775, 554, 886, 2443, 1722, 1607, 1212, 2117, 1874,
  95. 1455, 1029, 2300, 2110, 1219, 2935, 394, 885, 2444, 2154, 1175,
  96. };
  97. /*
  98. * Convert a ring element into NTT representation.
  99. *
  100. * The input v is an array of 256 uint16_t, giving the coefficients of
  101. * a polynomial in X, with v[i] being the coefficient of X^i.
  102. *
  103. * v is modified in place. On output, adjacent pairs of elements of v
  104. * give the coefficients of a smaller polynomial in X, with the pair
  105. * v[2i],v[2i+1] being the coefficients of X^0 and X^1 respectively in
  106. * the ring (Z/qZ)[X] / <X^2 - k>, where k = powers_odd_reversed_order[i].
  107. */
  108. static void mlkem_ntt(uint16_t *v)
  109. {
  110. const uint64_t Qrecip = reciprocal_for_reduction(Q);
  111. size_t next_power = 1;
  112. for (size_t len = 128; len >= 2; len /= 2) {
  113. for (size_t start = 0; start < 256; start += 2*len) {
  114. uint16_t mult = powers_reversed_order[next_power++];
  115. for (size_t j = start; j < start + len; j++) {
  116. uint16_t t = reduce(mult * v[j + len], Q, Qrecip);
  117. v[j + len] = reduce(v[j] + Q - t, Q, Qrecip);
  118. v[j] = reduce(v[j] + t, Q, Qrecip);
  119. }
  120. }
  121. }
  122. }
  123. /*
  124. * Convert back from NTT representation. Exactly inverts mlkem_ntt().
  125. */
  126. static void mlkem_inverse_ntt(uint16_t *v)
  127. {
  128. const uint64_t Qrecip = reciprocal_for_reduction(Q);
  129. size_t next_power = 127;
  130. for (size_t len = 2; len <= 128; len *= 2) {
  131. for (size_t start = 0; start < 256; start += 2*len) {
  132. uint16_t mult = powers_reversed_order[next_power--];
  133. for (size_t j = start; j < start + len; j++) {
  134. uint16_t t = v[j];
  135. v[j] = reduce(t + v[j + len], Q, Qrecip);
  136. v[j + len] = reduce(mult * (v[j + len] + Q - t), Q, Qrecip);
  137. }
  138. }
  139. }
  140. for (size_t i = 0; i < 256; i++)
  141. v[i] = reduce(v[i] * 3303, Q, Qrecip);
  142. }
  143. /*
  144. * Multiply two elements of R in NTT representation.
  145. *
  146. * The output can alias an input completely, but mustn't alias one
  147. * partially.
  148. */
  149. static void mlkem_multiply_ntts(
  150. uint16_t *out, const uint16_t *a, const uint16_t *b)
  151. {
  152. const uint64_t Qrecip = reciprocal_for_reduction(Q);
  153. for (size_t i = 0; i < 128; i++) {
  154. uint16_t a0 = a[2*i], a1 = a[2*i+1];
  155. uint16_t b0 = b[2*i], b1 = b[2*i+1];
  156. uint16_t mult = powers_odd_reversed_order[i];
  157. uint16_t a1b1 = reduce(a1 * b1, Q, Qrecip);
  158. out[2*i] = reduce(a0 * b0 + a1b1 * mult, Q, Qrecip);
  159. out[2*i+1] = reduce(a0 * b1 + a1 * b0, Q, Qrecip);
  160. }
  161. }
  162. /* ----------------------------------------------------------------------
  163. * Operations on matrices over the ring R.
  164. *
  165. * Most of these don't mind whether the matrix contains ring elements
  166. * represented directly as polynomials, or in NTT form. The exception
  167. * is that mlkem_matrix_mul requires it to be in NTT form (because
  168. * multiplying is a huge pain in the ordinary representation).
  169. */
  170. typedef struct mlkem_matrix mlkem_matrix;
  171. struct mlkem_matrix {
  172. unsigned nrows, ncols;
  173. /*
  174. * (nrows * ncols * 256) 16-bit integers. Each 256-word block
  175. * contains an element of R; the blocks are in in row-major order,
  176. * so that (data + 256*(ncols*y + x)) points at the start of the
  177. * element in row y column x.
  178. */
  179. uint16_t *data;
  180. };
  181. /* Storage used for multiple matrices, to free all at once afterwards */
  182. typedef struct mlkem_matrix_storage mlkem_matrix_storage;
  183. struct mlkem_matrix_storage {
  184. uint16_t *data;
  185. size_t n; /* number of ring elements */
  186. };
  187. /*
  188. * Allocate space for multiple matrices. All the arrays of uint16_t
  189. * are allocated as a single big array. This makes it easy to free the
  190. * whole lot in one go afterwards.
  191. *
  192. * It also means that the arrays have a fixed memory relationship to
  193. * each other, which matters not at all during live use, but
  194. * eliminates spurious control-flow divergences in testsc based on
  195. * accidents of memory allocation when vectorised code checks two
  196. * memory regions to see if they alias. (The compiler-generated
  197. * aliasing check must do two comparisons, one for each direction, and
  198. * the order of those two regions in memory affects whether the first
  199. * comparison decides the second one is necessary.)
  200. *
  201. * The variadic arguments for this function consist of a sequence of
  202. * triples (mlkem_matrix *m, int nrows, int ncols), terminated by a
  203. * null matrix pointer.
  204. */
  205. static void mlkem_matrix_alloc(mlkem_matrix_storage *storage, ...)
  206. {
  207. va_list ap;
  208. mlkem_matrix *m;
  209. storage->n = 0;
  210. va_start(ap, storage);
  211. while ((m = va_arg(ap, mlkem_matrix *)) != NULL) {
  212. int nrows = va_arg(ap, int), ncols = va_arg(ap, int);
  213. storage->n += nrows * ncols;
  214. }
  215. va_end(ap);
  216. storage->data = snewn(256 * storage->n, uint16_t);
  217. size_t pos = 0;
  218. va_start(ap, storage);
  219. while ((m = va_arg(ap, mlkem_matrix *)) != NULL) {
  220. int nrows = va_arg(ap, int), ncols = va_arg(ap, int);
  221. m->nrows = nrows;
  222. m->ncols = ncols;
  223. m->data = storage->data + 256 * pos;
  224. pos += nrows * ncols;
  225. }
  226. va_end(ap);
  227. }
  228. /* Clear and free the storage allocated by mlkem_matrix_alloc. */
  229. static void mlkem_matrix_storage_free(mlkem_matrix_storage *storage)
  230. {
  231. smemclr(storage->data, 256 * storage->n * sizeof(uint16_t));
  232. sfree(storage->data);
  233. }
  234. /* Add two matrices. */
  235. static void mlkem_matrix_add(mlkem_matrix *out, const mlkem_matrix *left,
  236. const mlkem_matrix *right)
  237. {
  238. const uint64_t Qrecip = reciprocal_for_reduction(Q);
  239. assert(out->nrows == left->nrows);
  240. assert(out->ncols == left->ncols);
  241. assert(out->nrows == right->nrows);
  242. assert(out->ncols == right->ncols);
  243. for (size_t i = 0; i < out->nrows; i++) {
  244. for (size_t j = 0; j < out->ncols; j++) {
  245. const uint16_t *lv = left->data + 256*(i * left->ncols + j);
  246. const uint16_t *rv = right->data + 256*(i * right->ncols + j);
  247. uint16_t *ov = out->data + 256*(i * out->ncols + j);
  248. for (size_t p = 0; p < 256; p++)
  249. ov[p] = reduce(lv[p] + rv[p] , Q, Qrecip);
  250. }
  251. }
  252. }
  253. /* Subtract matrices. */
  254. static void mlkem_matrix_sub(mlkem_matrix *out, const mlkem_matrix *left,
  255. const mlkem_matrix *right)
  256. {
  257. const uint64_t Qrecip = reciprocal_for_reduction(Q);
  258. assert(out->nrows == left->nrows);
  259. assert(out->ncols == left->ncols);
  260. assert(out->nrows == right->nrows);
  261. assert(out->ncols == right->ncols);
  262. for (size_t i = 0; i < out->nrows; i++) {
  263. for (size_t j = 0; j < out->ncols; j++) {
  264. const uint16_t *lv = left->data + 256*(i * left->ncols + j);
  265. const uint16_t *rv = right->data + 256*(i * right->ncols + j);
  266. uint16_t *ov = out->data + 256*(i * out->ncols + j);
  267. for (size_t p = 0; p < 256; p++)
  268. ov[p] = reduce(lv[p] + Q - rv[p] , Q, Qrecip);
  269. }
  270. }
  271. }
  272. /* Convert every element of a matrix into NTT representation. */
  273. static void mlkem_matrix_ntt(mlkem_matrix *m)
  274. {
  275. for (size_t i = 0; i < m->nrows * m->ncols; i++)
  276. mlkem_ntt(m->data + i * 256);
  277. }
  278. /* Convert every element of a matrix out of NTT representation. */
  279. static void mlkem_matrix_inverse_ntt(mlkem_matrix *m)
  280. {
  281. for (size_t i = 0; i < m->nrows * m->ncols; i++)
  282. mlkem_inverse_ntt(m->data + i * 256);
  283. }
  284. /*
  285. * Multiply two matrices, assuming their elements to be currently in
  286. * NTT representation.
  287. *
  288. * The left input must have the same number of columns as the right
  289. * has rows, in the usual fashion. The output matrix is overwritten.
  290. *
  291. * If 'left_transposed' is true then the left matrix is used as if
  292. * transposed.
  293. */
  294. static void mlkem_matrix_mul(mlkem_matrix *out, const mlkem_matrix *left,
  295. const mlkem_matrix *right, bool left_transposed)
  296. {
  297. const uint64_t Qrecip = reciprocal_for_reduction(Q);
  298. size_t left_nrows = (left_transposed ? left->ncols : left->nrows);
  299. size_t left_ncols = (left_transposed ? left->nrows : left->ncols);
  300. assert(out->nrows == left_nrows);
  301. assert(left_ncols == right->nrows);
  302. assert(right->ncols == out->ncols);
  303. uint16_t work[256];
  304. for (size_t i = 0; i < out->nrows; i++) {
  305. for (size_t j = 0; j < out->ncols; j++) {
  306. uint16_t *thisout = out->data + 256 * (i * out->ncols + j);
  307. memset(thisout, 0, 256 * sizeof(uint16_t));
  308. for (size_t k = 0; k < right->nrows; k++) {
  309. size_t left_index = left_transposed ?
  310. k * left->ncols + i : i * left->ncols + k;
  311. const uint16_t *lv = left->data + 256*left_index;
  312. const uint16_t *rv = right->data + 256*(k * right->ncols + j);
  313. mlkem_multiply_ntts(work, lv, rv);
  314. for (size_t p = 0; p < 256; p++)
  315. thisout[p] = reduce(thisout[p] + work[p], Q, Qrecip);
  316. }
  317. }
  318. }
  319. smemclr(work, sizeof(work));
  320. }
  321. /* ----------------------------------------------------------------------
  322. * Random sampling functions to make up various kinds of randomised
  323. * matrix and vector.
  324. */
  325. static void mlkem_sample_ntt(uint16_t *output, ptrlen seed); /* forward ref */
  326. /*
  327. * Invent a matrix based on a 32-bit random seed rho.
  328. *
  329. * This matrix is logically part of the public (encryption) key: it's
  330. * not transmitted explicitly, but the seed is, so that the receiver
  331. * can reconstruct the same matrix. As a result, this function
  332. * _doesn't_ have to worry about side channel resistance, or even
  333. * leaving data lying around in arrays.
  334. */
  335. static void mlkem_matrix_from_seed(mlkem_matrix *m, const void *rho)
  336. {
  337. for (unsigned r = 0; r < m->nrows; r++) {
  338. for (unsigned c = 0; c < m->ncols; c++) {
  339. unsigned char seedbuf[34];
  340. memcpy(seedbuf, rho, 32);
  341. seedbuf[32] = c;
  342. seedbuf[33] = r;
  343. mlkem_sample_ntt(m->data + 256 * (r * m->nrows + c),
  344. make_ptrlen(seedbuf, sizeof(seedbuf)));
  345. }
  346. }
  347. }
  348. /*
  349. * Invent a single element of the ring R, uniformly at random, derived
  350. * in a specified way from the input random seed.
  351. *
  352. * Used as a subroutine of mlkem_matrix_from_seed() above. So, for the
  353. * same reasons, this doesn't have to worry about side channels,
  354. * making the 'rejection sampling' generation technique easy.
  355. *
  356. * The name SampleNTT (in the official spec) reflects the fact that
  357. * the output elements are regarded as being in NTT representation.
  358. * But since the NTT is a bijection, and the sampling is from the
  359. * uniform probability distribution over R, nothing in this function
  360. * actually needs to worry about that.
  361. */
  362. static void mlkem_sample_ntt(uint16_t *output, ptrlen seed)
  363. {
  364. ShakeXOF *sx = shake128_xof_from_input(seed);
  365. unsigned char bytebuf[4];
  366. bytebuf[3] = '\0';
  367. for (size_t pos = 0; pos < 256 ;) {
  368. /* Read 3 bytes into the low-order end of bytebuf. The fourth
  369. * byte is always 0, so this gives us a random 24-bit integer. */
  370. shake_xof_read(sx, &bytebuf, 3);
  371. uint32_t random24 = GET_32BIT_LSB_FIRST(bytebuf);
  372. /*
  373. * Split that integer up into two 12-bit ones, and use each
  374. * one if it's in range (taking care for the second one that
  375. * we didn't just reach the end of the buffer).
  376. *
  377. * This function is only used for generating matrices from an
  378. * element of the public key, so we can use data-dependent
  379. * control flow here without worrying about giving away
  380. * secrets.
  381. */
  382. uint16_t d1 = random24 & 0xFFF;
  383. uint16_t d2 = random24 >> 12;
  384. if (d1 < Q)
  385. output[pos++] = d1;
  386. if (d2 < Q && pos < 256)
  387. output[pos++] = d2;
  388. }
  389. shake_xof_free(sx);
  390. }
  391. /*
  392. * Invent a random vector, with its elements _not_ in NTT
  393. * representation, and all the coefficients very small integers (a lot
  394. * smaller than q) of one sign or the other.
  395. *
  396. * eta is a parameter of the probability distribution, sigma is an
  397. * input 32-byte random seed. Each element of the vector is made by a
  398. * separate hash operation based on sigma plus a distinguishing
  399. * integer suffix; 'offset' indicates the starting point for those
  400. * suffixes, so that the ith output value has suffix (offset+i).
  401. */
  402. static void mlkem_matrix_poly_cbd(
  403. mlkem_matrix *v, int eta, const void *sigma, int offset)
  404. {
  405. const uint64_t Qrecip = reciprocal_for_reduction(Q);
  406. unsigned char seedbuf[33];
  407. memcpy(seedbuf, sigma, 32);
  408. unsigned char *randombuf = snewn(eta * 64, unsigned char);
  409. for (unsigned r = 0; r < v->nrows * v->ncols; r++) {
  410. seedbuf[32] = r + offset;
  411. ShakeXOF *sx = shake256_xof_from_input(make_ptrlen(seedbuf, 33));
  412. shake_xof_read(sx, randombuf, eta * 64);
  413. shake_xof_free(sx);
  414. for (size_t i = 0; i < 256; i++) {
  415. unsigned x = 0, y = 0;
  416. for (size_t j = 0; j < eta; j++) {
  417. size_t bitpos = 2 * i * eta + j;
  418. x += 1 & ((randombuf[bitpos >> 3]) >> (bitpos & 7));
  419. }
  420. for (size_t j = 0; j < eta; j++) {
  421. size_t bitpos = 2 * i * eta + eta + j;
  422. y += 1 & ((randombuf[bitpos >> 3]) >> (bitpos & 7));
  423. }
  424. v->data[256 * r + i] = reduce(x + Q - y, Q, Qrecip);
  425. }
  426. }
  427. smemclr(seedbuf, sizeof(seedbuf));
  428. smemclr(randombuf, eta * 64);
  429. sfree(randombuf);
  430. }
  431. /* ----------------------------------------------------------------------
  432. * Byte-encoding and decoding functions.
  433. */
  434. /*
  435. * Losslessly encode one or more elements of the ring R.
  436. *
  437. * Each polynomial coefficient, in the range [0,q), is represented as
  438. * a 12-bit integer. So encoding an entire ring element requires
  439. * (256*12)/8 = 384 bytes, and if that 384-byte string were
  440. * interpreted as a little-endian 3072-bit integer D, then the
  441. * coefficient of X^i could be recovered as (D >> (12*i)) & 0xFFF.
  442. *
  443. * The input is expected to be an array of 256*n uint16_t (often the
  444. * 'data' pointer in an mlkem_matrix). The output is 384*n bytes.
  445. */
  446. static void mlkem_byte_encode_lossless(
  447. void *outv, const uint16_t *in, size_t n)
  448. {
  449. unsigned char *out = (unsigned char *)outv;
  450. uint32_t buffer = 0, bufbits = 0;
  451. for (size_t i = 0; i < 256*n; i++) {
  452. buffer |= (uint32_t) in[i] << bufbits;
  453. bufbits += 12;
  454. while (bufbits >= 8) {
  455. *out++ = buffer & 0xFF;
  456. buffer >>= 8;
  457. bufbits -= 8;
  458. }
  459. }
  460. }
  461. /*
  462. * Decode a string written by mlkem_byte_encode_lossless.
  463. *
  464. * Each 12-bit value extracted from the input data is checked to make
  465. * sure it's in the range [0,q); if it's out of range, the whole
  466. * function fails and returns false. (But it need not do so in
  467. * constant time, because that's an "abandon the whole connection"
  468. * error, not a "subtly make things not work for the attacker" error.)
  469. */
  470. static bool mlkem_byte_decode_lossless(
  471. uint16_t *out, const void *inv, size_t n)
  472. {
  473. const unsigned char *in = (const unsigned char *)inv;
  474. uint32_t buffer = 0, bufbits = 0;
  475. for (size_t i = 0; i < 384*n; i++) {
  476. buffer |= (uint32_t) in[i] << bufbits;
  477. bufbits += 8;
  478. while (bufbits >= 12) {
  479. uint16_t value = buffer & 0xFFF;
  480. if (value >= Q)
  481. return false;
  482. *out++ = value;
  483. buffer >>= 12;
  484. bufbits -= 12;
  485. }
  486. }
  487. return true;
  488. }
  489. /*
  490. * Lossily encode one or more elements of R, using d bits for each
  491. * polynomial coefficient, for some d < 12. Each output d-bit value is
  492. * obtained as if by regarding the input coefficient as an integer in
  493. * the range [0,q), multiplying by 2^d/q, and rounding to the nearest
  494. * integer. (Since q is odd, 'round to nearest' can't have a tie.)
  495. *
  496. * This means that a large enough input coefficient can round up to
  497. * 2^d itself. In that situation the output d-bit value is 0.
  498. */
  499. static void mlkem_byte_encode_compressed(
  500. void *outv, const uint16_t *in, unsigned d, size_t n)
  501. {
  502. const uint64_t Qrecip = reciprocal_for_reduction(2*Q);
  503. unsigned char *out = (unsigned char *)outv;
  504. uint32_t buffer = 0, bufbits = 0;
  505. for (size_t i = 0; i < 256*n; i++) {
  506. uint32_t dividend = ((uint32_t)in[i] << (d+1)) + Q;
  507. uint32_t quotient;
  508. reduce_with_quot(dividend, &quotient, 2*Q, Qrecip);
  509. buffer |= (uint32_t) (quotient & ((1 << d) - 1)) << bufbits;
  510. bufbits += d;
  511. while (bufbits >= 8) {
  512. *out++ = buffer & 0xFF;
  513. buffer >>= 8;
  514. bufbits -= 8;
  515. }
  516. }
  517. }
  518. /*
  519. * Decode the lossily encoded output of mlkem_byte_encode_compressed.
  520. *
  521. * Each d-bit chunk of the encoding is converted back into a
  522. * polynomial coefficient as if by multiplying by q/2^d and then
  523. * rounding to nearest. Unlike the rounding in the encode step, this
  524. * _can_ have a tie when an unrounded value is half way between two
  525. * integers. Ties are broken by rounding up (as if the whole rounding
  526. * were performed by the simple rounding method of adding 1/2 and then
  527. * truncating).
  528. *
  529. * Unlike the lossless decode function, this one can't fail input
  530. * validation, because any d-bit value generates some legal
  531. * coefficient.
  532. */
  533. static void mlkem_byte_decode_compressed(
  534. uint16_t *out, const void *inv, unsigned d, size_t n)
  535. {
  536. const unsigned char *in = (const unsigned char *)inv;
  537. uint32_t buffer = 0, bufbits = 0;
  538. for (size_t i = 0; i < 32*d*n; i++) {
  539. buffer |= (uint32_t) in[i] << bufbits;
  540. bufbits += 8;
  541. while (bufbits >= d) {
  542. uint32_t value = buffer & ((1 << d) - 1);
  543. *out++ = (value * (2*Q) + (1 << d)) >> (d + 1);;
  544. buffer >>= d;
  545. bufbits -= d;
  546. }
  547. }
  548. }
  549. /* ----------------------------------------------------------------------
  550. * The top-level ML-KEM functions.
  551. */
  552. /*
  553. * Innermost keygen function, exposed for side-channel testing, with
  554. * separate random values rho (public) and sigma (private), so that
  555. * testsc can vary sigma while leaving rho the same.
  556. */
  557. void mlkem_keygen_rho_sigma(
  558. BinarySink *ek_out, BinarySink *dk_out, const mlkem_params *params,
  559. const void *rho, const void *sigma, const void *z)
  560. {
  561. mlkem_matrix_storage storage[1];
  562. mlkem_matrix a[1], s[1], e[1], t[1];
  563. mlkem_matrix_alloc(storage,
  564. a, params->k, params->k,
  565. s, params->k, 1,
  566. e, params->k, 1,
  567. t, params->k, 1,
  568. (mlkem_matrix *)NULL);
  569. /*
  570. * Make a random k x k matrix A (regarded as in NTT form).
  571. */
  572. mlkem_matrix_from_seed(a, rho);
  573. /*
  574. * Make two column vectors s and e, with all components having
  575. * small polynomial coefficients, and then convert them _into_ NTT
  576. * form.
  577. */
  578. mlkem_matrix_poly_cbd(s, params->eta_1, sigma, 0);
  579. mlkem_matrix_poly_cbd(e, params->eta_1, sigma, params->k);
  580. mlkem_matrix_ntt(s);
  581. mlkem_matrix_ntt(e);
  582. /*
  583. * Compute the vector t = As + e.
  584. */
  585. mlkem_matrix_mul(t, a, s, false);
  586. mlkem_matrix_add(t, t, e);
  587. /*
  588. * The encryption key is the vector t, plus the random seed rho
  589. * from which anyone can reconstruct the matrix A.
  590. */
  591. unsigned char ek[1568];
  592. mlkem_byte_encode_lossless(ek, t->data, params->k);
  593. memcpy(ek + 384 * params->k, rho, 32);
  594. size_t eklen = 384 * params->k + 32;
  595. put_data(ek_out, ek, eklen);
  596. /*
  597. * The decryption key (for the internal "K-PKE" public-key system)
  598. * is the vector s.
  599. */
  600. unsigned char dk[1536];
  601. mlkem_byte_encode_lossless(dk, s->data, params->k);
  602. size_t dklen = 384 * params->k;
  603. /*
  604. * The decapsulation key, for the full ML-KEM, consists of
  605. * - the decryption key as above
  606. * - the encryption key
  607. * - an extra hash of the encryption key
  608. * - the random value z used for "implicit rejection", aka
  609. * constructing a useless output value if tampering is
  610. * detected. (I think so an attacker can't tell the difference
  611. * between "I was rumbled" and "I was undetected but my attempt
  612. * didn't generate the right key">)
  613. */
  614. put_data(dk_out, dk, dklen);
  615. put_data(dk_out, ek, eklen);
  616. ssh_hash *h = ssh_hash_new(&ssh_sha3_256);
  617. put_data(h, ek, eklen);
  618. unsigned char ekhash[32];
  619. ssh_hash_final(h, ekhash);
  620. put_data(dk_out, ekhash, 32);
  621. put_data(dk_out, z, 32);
  622. mlkem_matrix_storage_free(storage);
  623. smemclr(ek, sizeof(ek));
  624. smemclr(ekhash, sizeof(ekhash));
  625. smemclr(dk, sizeof(dk));
  626. }
  627. /*
  628. * Internal keygen function as described in the official spec, taking
  629. * random values d and z and deterministically constructing a key from
  630. * them. The test vectors are expressed in terms of this.
  631. */
  632. void mlkem_keygen_internal(
  633. BinarySink *ek, BinarySink *dk, const mlkem_params *params,
  634. const void *d, const void *z)
  635. {
  636. /* Hash the input randomness d to make two 32-byte values rho and sigma */
  637. unsigned char rho_sigma[64];
  638. ssh_hash *h = ssh_hash_new(&ssh_sha3_512);
  639. put_data(h, d, 32);
  640. put_byte(h, params->k);
  641. ssh_hash_final(h, rho_sigma);
  642. mlkem_keygen_rho_sigma(ek, dk, params, rho_sigma, rho_sigma + 32, z);
  643. smemclr(rho_sigma, sizeof(rho_sigma));
  644. }
  645. /*
  646. * Keygen function for live use, making up the values at random.
  647. */
  648. void mlkem_keygen(
  649. BinarySink *ek, BinarySink *dk, const mlkem_params *params)
  650. {
  651. unsigned char dz[64];
  652. random_read(dz, 64);
  653. mlkem_keygen_internal(ek, dk, params, dz, dz + 32);
  654. smemclr(dz, sizeof(dz));
  655. }
  656. /*
  657. * Internal encapsulation function from the official spec, taking a
  658. * random value m as input and behaving deterministically. Again used
  659. * for test vectors.
  660. */
  661. bool mlkem_encaps_internal(
  662. BinarySink *c_out, BinarySink *k_out,
  663. const mlkem_params *params, ptrlen ek, const void *m)
  664. {
  665. mlkem_matrix_storage storage[1];
  666. mlkem_matrix t[1], a[1], y[1], e1[1], e2[1], mu[1], u[1], v[1];
  667. mlkem_matrix_alloc(storage,
  668. t, params->k, 1,
  669. a, params->k, params->k,
  670. y, params->k, 1,
  671. e1, params->k, 1,
  672. e2, 1, 1,
  673. mu, 1, 1,
  674. u, params->k, 1,
  675. v, 1, 1,
  676. (mlkem_matrix *)NULL);
  677. /*
  678. * Validate input: ek must be the correct length, and its encoded
  679. * ring elements must not include any 16-bit integer intended to
  680. * represent a value mod q which is not in fact in the range [0,q).
  681. *
  682. * We test the latter property by decoding the matrix t, and
  683. * checking the success status returned by the decode.
  684. */
  685. if (ek.len != 384 * params->k + 32 ||
  686. !mlkem_byte_decode_lossless(t->data, ek.ptr, params->k)) {
  687. mlkem_matrix_storage_free(storage);
  688. return false;
  689. }
  690. /*
  691. * Regenerate the same matrix A used by key generation, from the
  692. * seed string rho at the end of ek.
  693. */
  694. mlkem_matrix_from_seed(a, (const unsigned char *)ek.ptr + 384 * params->k);
  695. /*
  696. * Hash the input randomness m, to get the value k we'll use as
  697. * the output shared secret, plus some randomness for making up
  698. * the vectors below.
  699. */
  700. unsigned char kr[64];
  701. unsigned char ekhash[32];
  702. ssh_hash *h;
  703. /* Hash the encryption key */
  704. h = ssh_hash_new(&ssh_sha3_256);
  705. put_datapl(h, ek);
  706. ssh_hash_final(h, ekhash);
  707. /* Hash the input randomness m with that hash */
  708. h = ssh_hash_new(&ssh_sha3_512);
  709. put_data(h, m, 32);
  710. put_data(h, ekhash, 32);
  711. ssh_hash_final(h, kr);
  712. const unsigned char *k = kr, *r = kr + 32;
  713. /*
  714. * Invent random k-element vectors y and e1, and a random scalar
  715. * e2 (here represented as a 1x1 matrix for the sake of not
  716. * proliferating internal helper functions). All are generated by
  717. * poly_cbd (i.e. their ring elements have polynomial coefficients
  718. * of small magnitude). y needs to be in NTT form.
  719. *
  720. * These generations all use r as their seed, which was the second
  721. * half of the 64-byte hash of the input m. We pass different
  722. * 'offset' values to mlkem_matrix_poly_cbd() to ensure the
  723. * generations are probabilistically independent.
  724. */
  725. mlkem_matrix_poly_cbd(y, params->eta_1, r, 0);
  726. mlkem_matrix_ntt(y);
  727. mlkem_matrix_poly_cbd(e1, params->eta_2, r, params->k);
  728. mlkem_matrix_poly_cbd(e2, params->eta_2, r, 2 * params->k);
  729. /*
  730. * Invent a random scalar mu (again imagined as a 1x1 matrix),
  731. * this time by doing lossy decompression of the random value m at
  732. * 1 bit per polynomial coefficient. That is, all the polynomial
  733. * coefficients of mu are either 0 or 1665 = (q+1)/2.
  734. *
  735. * This generation reuses the _input_ random value m, not either
  736. * half of the hash we made of it.
  737. */
  738. mlkem_byte_decode_compressed(mu->data, m, 1, 1);
  739. /*
  740. * Calculate a k-element vector u = A^T y + e1.
  741. *
  742. * A and y are in NTT representation, but e1 is not, and we don't
  743. * want the output to be in NTT form either. So we perform an
  744. * inverse NTT after the multiplication.
  745. */
  746. mlkem_matrix_mul(u, a, y, true); /* regard a as transposed */
  747. mlkem_matrix_inverse_ntt(u);
  748. mlkem_matrix_add(u, u, e1);
  749. /*
  750. * Calculate a scalar v = t^T y + e2 + mu.
  751. *
  752. * (t and y are column vectors, so t^T y is just a scalar - you
  753. * could think of it as the dot product t.y if you preferred.)
  754. *
  755. * Similarly to above, we multiply t and y which are in NTT
  756. * representation, and then perform an inverse NTT before adding
  757. * e2 and mu, which aren't.
  758. */
  759. mlkem_matrix_mul(v, t, y, true); /* regard t as transposed */
  760. mlkem_matrix_inverse_ntt(v);
  761. mlkem_matrix_add(v, v, e2);
  762. mlkem_matrix_add(v, v, mu);
  763. /*
  764. * The ciphertext consists of u and v, both encoded lossily, with
  765. * different numbers of bits retained per element.
  766. */
  767. char c[1568];
  768. mlkem_byte_encode_compressed(c, u->data, params->d_u, params->k);
  769. mlkem_byte_encode_compressed(c + 32 * params->k * params->d_u,
  770. v->data, params->d_v, 1);
  771. put_data(c_out, c, 32 * (params->k * params->d_u + params->d_v));
  772. /*
  773. * The output shared secret is just half of the hash of m (the
  774. * first half, which we didn't use for generating vectors above).
  775. */
  776. put_data(k_out, k, 32);
  777. smemclr(kr, sizeof(kr));
  778. mlkem_matrix_storage_free(storage);
  779. return true;
  780. }
  781. /*
  782. * Encapsulation function for live use, using the real RNG..
  783. */
  784. bool mlkem_encaps(BinarySink *ciphertext, BinarySink *kout,
  785. const mlkem_params *params, ptrlen ek)
  786. {
  787. unsigned char m[32];
  788. random_read(m, 32);
  789. bool success = mlkem_encaps_internal(ciphertext, kout, params, ek, m);
  790. smemclr(m, sizeof(m));
  791. return success;
  792. }
  793. /*
  794. * Decapsulation.
  795. */
  796. bool mlkem_decaps(BinarySink *k_out, const mlkem_params *params,
  797. ptrlen dk, ptrlen c)
  798. {
  799. /*
  800. * Validation: check the input strings are the right lengths.
  801. */
  802. if (dk.len != 768 * params->k + 96)
  803. return false;
  804. if (c.len != 32 * (params->d_u * params->k + params->d_v))
  805. return false;
  806. /*
  807. * Further validation: extract the encryption key from the middle
  808. * of dk, hash it, and check the hash matches.
  809. */
  810. const unsigned char *dkp = (const unsigned char *)dk.ptr;
  811. const unsigned char *cp = (const unsigned char *)c.ptr;
  812. ptrlen ek = make_ptrlen(dkp + 384*params->k, 384*params->k + 32);
  813. ssh_hash *h;
  814. unsigned char ekhash[32];
  815. h = ssh_hash_new(&ssh_sha3_256);
  816. put_datapl(h, ek);
  817. ssh_hash_final(h, ekhash);
  818. if (!smemeq(ekhash, dkp + 768*params->k + 32, 32))
  819. return false;
  820. mlkem_matrix_storage storage[1];
  821. mlkem_matrix u[1], v[1], s[1], w[1];
  822. mlkem_matrix_alloc(storage,
  823. u, params->k, 1,
  824. v, 1, 1,
  825. s, params->k, 1,
  826. w, 1, 1,
  827. (mlkem_matrix *)NULL);
  828. /*
  829. * Decode the vector u and the scalar v from the ciphertext. These
  830. * won't come out exactly the same as the originals, because of
  831. * the lossy compression.
  832. */
  833. mlkem_byte_decode_compressed(u->data, cp, params->d_u, params->k);
  834. mlkem_matrix_ntt(u);
  835. mlkem_byte_decode_compressed(v->data, cp + 32 * params->d_u * params->k,
  836. params->d_v, 1);
  837. /*
  838. * Decode the vector s from the private key.
  839. */
  840. mlkem_byte_decode_lossless(s->data, dkp, params->k);
  841. /*
  842. * Calculate the scalar w = v - s^T u.
  843. *
  844. * s and u are in NTT representation, but v isn't, so we
  845. * inverse-NTT the product before doing the subtraction. Therefore
  846. * w is not in NTT form either.
  847. */
  848. mlkem_matrix_mul(w, s, u, true); /* regard s as transposed */
  849. mlkem_matrix_inverse_ntt(w);
  850. mlkem_matrix_sub(w, v, w);
  851. /*
  852. * The aim is that this reconstructs something close enough to the
  853. * random vector mu that was made from the input secret m to
  854. * encapsulation, on the grounds that mu's polynomial coefficients
  855. * were very widely separated (on opposite sides of the cyclic
  856. * additive group of Z/qZ) and the noise added during encryption
  857. * all had _small_ polynomial coefficients.
  858. *
  859. * So we now re-encode this lossily at 1 bit per polynomial
  860. * coefficient, and hope that it reconstructs the actual string m.
  861. *
  862. * However, this _is_ only a hope! The ML-KEM decryption is not a
  863. * true mathematical inverse to encryption. With extreme bad luck,
  864. * the noise can add up enough that it flips a bit of m, and
  865. * everything fails. The parameters are chosen to make this happen
  866. * with negligible probability (the same kind of low probability
  867. * that makes you not worry about spontaneous hash collisions),
  868. * but it's not actually impossible.
  869. */
  870. unsigned char m[32];
  871. mlkem_byte_encode_compressed(m, w->data, 1, 1);
  872. /*
  873. * Now do the key _encapsulation_ again from scratch, using that
  874. * secret m as input, and check that it generates the identical
  875. * ciphertext. This should catch the above theoretical failure,
  876. * but also, it's a defence against malicious intervention in the
  877. * key exchange.
  878. *
  879. * This is also where we get the output secret k from: the
  880. * encapsulation function creates it as half of the hash of m.
  881. */
  882. unsigned char c_regen[1568], k[32];
  883. buffer_sink c_sink[1], k_sink[1];
  884. buffer_sink_init(c_sink, c_regen, sizeof(c_regen));
  885. buffer_sink_init(k_sink, k, sizeof(k));
  886. bool success = mlkem_encaps_internal(
  887. BinarySink_UPCAST(c_sink), BinarySink_UPCAST(k_sink), params, ek, m);
  888. /* If any application of ML-KEM uses a dk given to it by someone
  889. * else, then perhaps they have to worry about being given an
  890. * invalid one? But in our application we always expect this to
  891. * succeed, because dk is generated and used at the same end of
  892. * the SSH connection, within the same process, and nobody is
  893. * interfering with it. */
  894. assert(success && "We generated this dk ourselves, how can it be bad?");
  895. /*
  896. * If mlkem_encaps_internal returned success but delivered the
  897. * wrong ciphertext, that's a failure, but we must be careful not
  898. * to let the attacker know exactly what went wrong. So we
  899. * generate a plausible but wrong substitute output secret.
  900. *
  901. * k_reject is that secret; for constant-time reasons we generate
  902. * it unconditionally.
  903. */
  904. unsigned char k_reject[32];
  905. h = ssh_hash_new(&ssh_shake256_32bytes);
  906. put_data(h, dkp + 768 * params->k + 64, 32);
  907. put_datapl(h, c);
  908. ssh_hash_final(h, k_reject);
  909. /*
  910. * Now replace k with k_reject if the ciphertexts didn't match.
  911. */
  912. assert((void *)c_sink->out == (void *)(c_regen + c.len));
  913. unsigned match = smemeq(c.ptr, c_regen, c.len);
  914. unsigned mask = match - 1;
  915. for (size_t i = 0; i < 32; i++)
  916. k[i] ^= mask & (k[i] ^ k_reject[i]);
  917. /*
  918. * And we're done! Free everything and return whichever secret we
  919. * chose.
  920. */
  921. put_data(k_out, k, 32);
  922. mlkem_matrix_storage_free(storage);
  923. smemclr(m, sizeof(m));
  924. smemclr(c_regen, sizeof(c_regen));
  925. smemclr(k, sizeof(k));
  926. smemclr(k_reject, sizeof(k_reject));
  927. return true;
  928. }
  929. /* ----------------------------------------------------------------------
  930. * Implement the pq_kemalg vtable in terms of the above functions.
  931. */
  932. struct mlkem_dk {
  933. strbuf *encoded;
  934. pq_kem_dk dk;
  935. };
  936. static pq_kem_dk *mlkem_vt_keygen(const pq_kemalg *alg, BinarySink *ek)
  937. {
  938. struct mlkem_dk *mdk = snew(struct mlkem_dk);
  939. mdk->dk.vt = alg;
  940. mdk->encoded = strbuf_new_nm();
  941. mlkem_keygen(ek, BinarySink_UPCAST(mdk->encoded), alg->extra);
  942. return &mdk->dk;
  943. }
  944. static bool mlkem_vt_encaps(const pq_kemalg *alg, BinarySink *c, BinarySink *k,
  945. ptrlen ek)
  946. {
  947. return mlkem_encaps(c, k, alg->extra, ek);
  948. }
  949. static bool mlkem_vt_decaps(pq_kem_dk *dk, BinarySink *k, ptrlen c)
  950. {
  951. struct mlkem_dk *mdk = container_of(dk, struct mlkem_dk, dk);
  952. return mlkem_decaps(k, mdk->dk.vt->extra,
  953. ptrlen_from_strbuf(mdk->encoded), c);
  954. }
  955. static void mlkem_vt_free_dk(pq_kem_dk *dk)
  956. {
  957. struct mlkem_dk *mdk = container_of(dk, struct mlkem_dk, dk);
  958. strbuf_free(mdk->encoded);
  959. sfree(mdk);
  960. }
  961. const pq_kemalg ssh_mlkem512 = {
  962. .keygen = mlkem_vt_keygen,
  963. .encaps = mlkem_vt_encaps,
  964. .decaps = mlkem_vt_decaps,
  965. .free_dk = mlkem_vt_free_dk,
  966. .extra = &mlkem_params_512,
  967. .description = "ML-KEM-512",
  968. .ek_len = 384 * 2 + 32,
  969. .c_len = 32 * (10 * 2 + 4),
  970. };
  971. const pq_kemalg ssh_mlkem768 = {
  972. .keygen = mlkem_vt_keygen,
  973. .encaps = mlkem_vt_encaps,
  974. .decaps = mlkem_vt_decaps,
  975. .free_dk = mlkem_vt_free_dk,
  976. .extra = &mlkem_params_768,
  977. .description = "ML-KEM-768",
  978. .ek_len = 384 * 3 + 32,
  979. .c_len = 32 * (10 * 3 + 4),
  980. };
  981. const pq_kemalg ssh_mlkem1024 = {
  982. .keygen = mlkem_vt_keygen,
  983. .encaps = mlkem_vt_encaps,
  984. .decaps = mlkem_vt_decaps,
  985. .free_dk = mlkem_vt_free_dk,
  986. .extra = &mlkem_params_1024,
  987. .description = "ML-KEM-1024",
  988. .ek_len = 384 * 4 + 32,
  989. .c_len = 32 * (11 * 4 + 5),
  990. };