ml_kem.c 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050
  1. /*
  2. * Copyright 2024-2025 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the Apache License 2.0 (the "License"). You may not use
  5. * this file except in compliance with the License. You can obtain a copy
  6. * in the file LICENSE in the source distribution or at
  7. * https://www.openssl.org/source/license.html
  8. */
  9. #include <openssl/byteorder.h>
  10. #include <openssl/rand.h>
  11. #include <openssl/proverr.h>
  12. #include "crypto/ml_kem.h"
  13. #include "internal/common.h"
  14. #include "internal/constant_time.h"
  15. #include "internal/sha3.h"
  16. #if defined(OPENSSL_CONSTANT_TIME_VALIDATION)
  17. #include <valgrind/memcheck.h>
  18. #endif
  19. #if ML_KEM_SEED_BYTES != ML_KEM_SHARED_SECRET_BYTES + ML_KEM_RANDOM_BYTES
  20. # error "ML-KEM keygen seed length != shared secret + random bytes length"
  21. #endif
  22. #if ML_KEM_SHARED_SECRET_BYTES != ML_KEM_RANDOM_BYTES
  23. # error "Invalid unequal lengths of ML-KEM shared secret and random inputs"
  24. #endif
  25. #if UINT_MAX < UINT32_MAX
  26. # error "Unsupported compiler: sizeof(unsigned int) < sizeof(uint32_t)"
  27. #endif
  28. /* Handy function-like bit-extraction macros */
  29. #define bit0(b) ((b) & 1)
  30. #define bitn(n, b) (((b) >> n) & 1)
  31. /*
  32. * 12 bits are sufficient to losslessly represent values in [0, q-1].
  33. * INVERSE_DEGREE is (n/2)^-1 mod q; used in inverse NTT.
  34. */
  35. #define DEGREE ML_KEM_DEGREE
  36. #define INVERSE_DEGREE (ML_KEM_PRIME - 2 * 13)
  37. #define LOG2PRIME 12
  38. #define BARRETT_SHIFT (2 * LOG2PRIME)
  39. #ifdef SHA3_BLOCKSIZE
  40. # define SHAKE128_BLOCKSIZE SHA3_BLOCKSIZE(128)
  41. #endif
  42. /*
  43. * Return whether a value that can only be 0 or 1 is non-zero, in constant time
  44. * in practice! The return value is a mask that is all ones if true, and all
  45. * zeros otherwise (twos-complement arithmentic assumed for unsigned values).
  46. *
  47. * Although this is used in constant-time selects, we omit a value barrier
  48. * here. Value barriers impede auto-vectorization (likely because it forces
  49. * the value to transit through a general-purpose register). On AArch64, this
  50. * is a difference of 2x.
  51. *
  52. * We usually add value barriers to selects because Clang turns consecutive
  53. * selects with the same condition into a branch instead of CMOV/CSEL. This
  54. * condition does not occur in Kyber, so omitting it seems to be safe so far,
  55. * but see |cbd_2|, |cbd_3|, where reduction needs to be specialised to the
  56. * sign of the input, rather than adding |q| in advance, and using the generic
  57. * |reduce_once|. (David Benjamin, Chromium)
  58. */
  59. #if 0
  60. # define constish_time_non_zero(b) (~constant_time_is_zero(b));
  61. #else
  62. # define constish_time_non_zero(b) (0u - (b))
  63. #endif
  64. /*
  65. * The scalar rejection-sampling buffer size needs to be a multiple of 12, but
  66. * is otherwise arbitrary, the preferred block size matches the internal buffer
  67. * size of SHAKE128, avoiding internal buffering and copying in SHAKE128. That
  68. * block size of (1600 - 256)/8 bytes, or 168, just happens to divide by 12!
  69. *
  70. * If the blocksize is unknown, or is not divisible by 12, 168 is used as a
  71. * fallback.
  72. */
  73. #if defined(SHAKE128_BLOCKSIZE) && (SHAKE128_BLOCKSIZE) % 12 == 0
  74. # define SCALAR_SAMPLING_BUFSIZE (SHAKE128_BLOCKSIZE)
  75. #else
  76. # define SCALAR_SAMPLING_BUFSIZE 168
  77. #endif
  78. /*
  79. * Structure of keys
  80. */
  81. typedef struct ossl_ml_kem_scalar_st {
  82. /* On every function entry and exit, 0 <= c[i] < ML_KEM_PRIME. */
  83. uint16_t c[ML_KEM_DEGREE];
  84. } scalar;
  85. /* Key material allocation layout */
  86. #define DECLARE_ML_KEM_KEYDATA(name, rank, private_sz) \
  87. struct name##_alloc { \
  88. /* Public vector |t| */ \
  89. scalar tbuf[(rank)]; \
  90. /* Pre-computed matrix |m| (FIPS 203 |A| transpose) */ \
  91. scalar mbuf[(rank)*(rank)] \
  92. /* optional private key data */ \
  93. private_sz \
  94. }
  95. /* Declare variant-specific public and private storage */
  96. #define DECLARE_ML_KEM_VARIANT_KEYDATA(bits) \
  97. DECLARE_ML_KEM_KEYDATA(pubkey_##bits, ML_KEM_##bits##_RANK,;); \
  98. DECLARE_ML_KEM_KEYDATA(prvkey_##bits, ML_KEM_##bits##_RANK,;\
  99. scalar sbuf[ML_KEM_##bits##_RANK]; \
  100. uint8_t zbuf[2 * ML_KEM_RANDOM_BYTES];)
  101. DECLARE_ML_KEM_VARIANT_KEYDATA(512);
  102. DECLARE_ML_KEM_VARIANT_KEYDATA(768);
  103. DECLARE_ML_KEM_VARIANT_KEYDATA(1024);
  104. #undef DECLARE_ML_KEM_VARIANT_KEYDATA
  105. #undef DECLARE_ML_KEM_KEYDATA
  106. typedef __owur
  107. int (*CBD_FUNC)(scalar *out, uint8_t in[ML_KEM_RANDOM_BYTES + 1],
  108. EVP_MD_CTX *mdctx, const ML_KEM_KEY *key);
  109. static void scalar_encode(uint8_t *out, const scalar *s, int bits);
  110. /*
  111. * The wire-form of a losslessly encoded vector uses 12-bits per element.
  112. *
  113. * The wire-form public key consists of the lossless encoding of the public
  114. * vector |t|, followed by the public seed |rho|.
  115. *
  116. * Our serialised private key concatenates serialisations of the private vector
  117. * |s|, the public key, the public key hash, and the failure secret |z|.
  118. */
  119. #define VECTOR_BYTES(b) ((3 * DEGREE / 2) * ML_KEM_##b##_RANK)
  120. #define PUBKEY_BYTES(b) (VECTOR_BYTES(b) + ML_KEM_RANDOM_BYTES)
  121. #define PRVKEY_BYTES(b) (2 * PUBKEY_BYTES(b) + ML_KEM_PKHASH_BYTES)
  122. /*
  123. * Encapsulation produces a vector "u" and a scalar "v", whose coordinates
  124. * (numbers modulo the ML-KEM prime "q") are lossily encoded using as "du" and
  125. * "dv" bits, respectively. This encoding is the ciphertext input for
  126. * decapsulation.
  127. */
  128. #define U_VECTOR_BYTES(b) ((DEGREE / 8) * ML_KEM_##b##_DU * ML_KEM_##b##_RANK)
  129. #define V_SCALAR_BYTES(b) ((DEGREE / 8) * ML_KEM_##b##_DV)
  130. #define CTEXT_BYTES(b) (U_VECTOR_BYTES(b) + V_SCALAR_BYTES(b))
  131. #if defined(OPENSSL_CONSTANT_TIME_VALIDATION)
  132. /*
  133. * CONSTTIME_SECRET takes a pointer and a number of bytes and marks that region
  134. * of memory as secret. Secret data is tracked as it flows to registers and
  135. * other parts of a memory. If secret data is used as a condition for a branch,
  136. * or as a memory index, it will trigger warnings in valgrind.
  137. */
  138. # define CONSTTIME_SECRET(ptr, len) VALGRIND_MAKE_MEM_UNDEFINED(ptr, len)
  139. /*
  140. * CONSTTIME_DECLASSIFY takes a pointer and a number of bytes and marks that
  141. * region of memory as public. Public data is not subject to constant-time
  142. * rules.
  143. */
  144. # define CONSTTIME_DECLASSIFY(ptr, len) VALGRIND_MAKE_MEM_DEFINED(ptr, len)
  145. #else
  146. # define CONSTTIME_SECRET(ptr, len)
  147. # define CONSTTIME_DECLASSIFY(ptr, len)
  148. #endif
  149. /*
  150. * Indices of slots in the vinfo tables below
  151. */
  152. #define ML_KEM_512_VINFO 0
  153. #define ML_KEM_768_VINFO 1
  154. #define ML_KEM_1024_VINFO 2
  155. /*
  156. * Per-variant fixed parameters
  157. */
  158. static const ML_KEM_VINFO vinfo_map[3] = {
  159. {
  160. "ML-KEM-512",
  161. PRVKEY_BYTES(512),
  162. sizeof(struct prvkey_512_alloc),
  163. PUBKEY_BYTES(512),
  164. sizeof(struct pubkey_512_alloc),
  165. CTEXT_BYTES(512),
  166. VECTOR_BYTES(512),
  167. U_VECTOR_BYTES(512),
  168. EVP_PKEY_ML_KEM_512,
  169. ML_KEM_512_BITS,
  170. ML_KEM_512_RANK,
  171. ML_KEM_512_DU,
  172. ML_KEM_512_DV,
  173. ML_KEM_512_SECBITS
  174. },
  175. {
  176. "ML-KEM-768",
  177. PRVKEY_BYTES(768),
  178. sizeof(struct prvkey_768_alloc),
  179. PUBKEY_BYTES(768),
  180. sizeof(struct pubkey_768_alloc),
  181. CTEXT_BYTES(768),
  182. VECTOR_BYTES(768),
  183. U_VECTOR_BYTES(768),
  184. EVP_PKEY_ML_KEM_768,
  185. ML_KEM_768_BITS,
  186. ML_KEM_768_RANK,
  187. ML_KEM_768_DU,
  188. ML_KEM_768_DV,
  189. ML_KEM_768_SECBITS
  190. },
  191. {
  192. "ML-KEM-1024",
  193. PRVKEY_BYTES(1024),
  194. sizeof(struct prvkey_1024_alloc),
  195. PUBKEY_BYTES(1024),
  196. sizeof(struct pubkey_1024_alloc),
  197. CTEXT_BYTES(1024),
  198. VECTOR_BYTES(1024),
  199. U_VECTOR_BYTES(1024),
  200. EVP_PKEY_ML_KEM_1024,
  201. ML_KEM_1024_BITS,
  202. ML_KEM_1024_RANK,
  203. ML_KEM_1024_DU,
  204. ML_KEM_1024_DV,
  205. ML_KEM_1024_SECBITS
  206. }
  207. };
  208. /*
  209. * Remainders modulo `kPrime`, for sufficiently small inputs, are computed in
  210. * constant time via Barrett reduction, and a final call to reduce_once(),
  211. * which reduces inputs that are at most 2*kPrime and is also constant-time.
  212. */
  213. static const int kPrime = ML_KEM_PRIME;
  214. static const unsigned int kBarrettShift = BARRETT_SHIFT;
  215. static const size_t kBarrettMultiplier = (1 << BARRETT_SHIFT) / ML_KEM_PRIME;
  216. static const uint16_t kHalfPrime = (ML_KEM_PRIME - 1) / 2;
  217. static const uint16_t kInverseDegree = INVERSE_DEGREE;
  218. /*
  219. * Python helper:
  220. *
  221. * p = 3329
  222. * def bitreverse(i):
  223. * ret = 0
  224. * for n in range(7):
  225. * bit = i & 1
  226. * ret <<= 1
  227. * ret |= bit
  228. * i >>= 1
  229. * return ret
  230. */
  231. /*-
  232. * First precomputed array from Appendix A of FIPS 203, or else Python:
  233. * kNTTRoots = [pow(17, bitreverse(i), p) for i in range(128)]
  234. */
  235. static const uint16_t kNTTRoots[128] = {
  236. 1, 1729, 2580, 3289, 2642, 630, 1897, 848,
  237. 1062, 1919, 193, 797, 2786, 3260, 569, 1746,
  238. 296, 2447, 1339, 1476, 3046, 56, 2240, 1333,
  239. 1426, 2094, 535, 2882, 2393, 2879, 1974, 821,
  240. 289, 331, 3253, 1756, 1197, 2304, 2277, 2055,
  241. 650, 1977, 2513, 632, 2865, 33, 1320, 1915,
  242. 2319, 1435, 807, 452, 1438, 2868, 1534, 2402,
  243. 2647, 2617, 1481, 648, 2474, 3110, 1227, 910,
  244. 17, 2761, 583, 2649, 1637, 723, 2288, 1100,
  245. 1409, 2662, 3281, 233, 756, 2156, 3015, 3050,
  246. 1703, 1651, 2789, 1789, 1847, 952, 1461, 2687,
  247. 939, 2308, 2437, 2388, 733, 2337, 268, 641,
  248. 1584, 2298, 2037, 3220, 375, 2549, 2090, 1645,
  249. 1063, 319, 2773, 757, 2099, 561, 2466, 2594,
  250. 2804, 1092, 403, 1026, 1143, 2150, 2775, 886,
  251. 1722, 1212, 1874, 1029, 2110, 2935, 885, 2154,
  252. };
  253. /*
  254. * InverseNTTRoots = [pow(17, -bitreverse(i), p) for i in range(128)]
  255. * Listed in order of use in the inverse NTT loop (index 0 is skipped):
  256. *
  257. * 0, 64, 65, ..., 127, 32, 33, ..., 63, 16, 17, ..., 31, 8, 9, ...
  258. */
  259. static const uint16_t kInverseNTTRoots[128] = {
  260. 1, 1175, 2444, 394, 1219, 2300, 1455, 2117,
  261. 1607, 2443, 554, 1179, 2186, 2303, 2926, 2237,
  262. 525, 735, 863, 2768, 1230, 2572, 556, 3010,
  263. 2266, 1684, 1239, 780, 2954, 109, 1292, 1031,
  264. 1745, 2688, 3061, 992, 2596, 941, 892, 1021,
  265. 2390, 642, 1868, 2377, 1482, 1540, 540, 1678,
  266. 1626, 279, 314, 1173, 2573, 3096, 48, 667,
  267. 1920, 2229, 1041, 2606, 1692, 680, 2746, 568,
  268. 3312, 2419, 2102, 219, 855, 2681, 1848, 712,
  269. 682, 927, 1795, 461, 1891, 2877, 2522, 1894,
  270. 1010, 1414, 2009, 3296, 464, 2697, 816, 1352,
  271. 2679, 1274, 1052, 1025, 2132, 1573, 76, 2998,
  272. 3040, 2508, 1355, 450, 936, 447, 2794, 1235,
  273. 1903, 1996, 1089, 3273, 283, 1853, 1990, 882,
  274. 3033, 1583, 2760, 69, 543, 2532, 3136, 1410,
  275. 2267, 2481, 1432, 2699, 687, 40, 749, 1600,
  276. };
  277. /*
  278. * Second precomputed array from Appendix A of FIPS 203 (normalised positive),
  279. * or else Python:
  280. * ModRoots = [pow(17, 2*bitreverse(i) + 1, p) for i in range(128)]
  281. */
  282. static const uint16_t kModRoots[128] = {
  283. 17, 3312, 2761, 568, 583, 2746, 2649, 680, 1637, 1692, 723, 2606,
  284. 2288, 1041, 1100, 2229, 1409, 1920, 2662, 667, 3281, 48, 233, 3096,
  285. 756, 2573, 2156, 1173, 3015, 314, 3050, 279, 1703, 1626, 1651, 1678,
  286. 2789, 540, 1789, 1540, 1847, 1482, 952, 2377, 1461, 1868, 2687, 642,
  287. 939, 2390, 2308, 1021, 2437, 892, 2388, 941, 733, 2596, 2337, 992,
  288. 268, 3061, 641, 2688, 1584, 1745, 2298, 1031, 2037, 1292, 3220, 109,
  289. 375, 2954, 2549, 780, 2090, 1239, 1645, 1684, 1063, 2266, 319, 3010,
  290. 2773, 556, 757, 2572, 2099, 1230, 561, 2768, 2466, 863, 2594, 735,
  291. 2804, 525, 1092, 2237, 403, 2926, 1026, 2303, 1143, 2186, 2150, 1179,
  292. 2775, 554, 886, 2443, 1722, 1607, 1212, 2117, 1874, 1455, 1029, 2300,
  293. 2110, 1219, 2935, 394, 885, 2444, 2154, 1175,
  294. };
  295. /*
  296. * single_keccak hashes |inlen| bytes from |in| and writes |outlen| bytes of
  297. * output to |out|. If the |md| specifies a fixed-output function, like
  298. * SHA3-256, then |outlen| must be the correct length for that function.
  299. */
  300. static __owur
  301. int single_keccak(uint8_t *out, size_t outlen, const uint8_t *in, size_t inlen,
  302. EVP_MD_CTX *mdctx)
  303. {
  304. unsigned int sz = (unsigned int) outlen;
  305. if (!EVP_DigestUpdate(mdctx, in, inlen))
  306. return 0;
  307. if (EVP_MD_xof(EVP_MD_CTX_get0_md(mdctx)))
  308. return EVP_DigestFinalXOF(mdctx, out, outlen);
  309. return EVP_DigestFinal_ex(mdctx, out, &sz)
  310. && ossl_assert((size_t) sz == outlen);
  311. }
  312. /*
  313. * FIPS 203, Section 4.1, equation (4.3): PRF. Takes 32+1 input bytes, and uses
  314. * SHAKE256 to produce the input to SamplePolyCBD_eta: FIPS 203, algorithm 8.
  315. */
  316. static __owur
  317. int prf(uint8_t *out, size_t len, const uint8_t in[ML_KEM_RANDOM_BYTES + 1],
  318. EVP_MD_CTX *mdctx, const ML_KEM_KEY *key)
  319. {
  320. return EVP_DigestInit_ex(mdctx, key->shake256_md, NULL)
  321. && single_keccak(out, len, in, ML_KEM_RANDOM_BYTES + 1, mdctx);
  322. }
  323. /*
  324. * FIPS 203, Section 4.1, equation (4.4): H. SHA3-256 hash of a variable
  325. * length input, producing 32 bytes of output.
  326. */
  327. static __owur
  328. int hash_h(uint8_t out[ML_KEM_PKHASH_BYTES], const uint8_t *in, size_t len,
  329. EVP_MD_CTX *mdctx, const ML_KEM_KEY *key)
  330. {
  331. return EVP_DigestInit_ex(mdctx, key->sha3_256_md, NULL)
  332. && single_keccak(out, ML_KEM_PKHASH_BYTES, in, len, mdctx);
  333. }
  334. /* Incremental hash_h of expanded public key */
  335. static int
  336. hash_h_pubkey(uint8_t pkhash[ML_KEM_PKHASH_BYTES],
  337. EVP_MD_CTX *mdctx, ML_KEM_KEY *key)
  338. {
  339. const ML_KEM_VINFO *vinfo = key->vinfo;
  340. const scalar *t = key->t, *end = t + vinfo->rank;
  341. unsigned int sz;
  342. if (!EVP_DigestInit_ex(mdctx, key->sha3_256_md, NULL))
  343. return 0;
  344. do {
  345. uint8_t buf[3 * DEGREE / 2];
  346. scalar_encode(buf, t++, 12);
  347. if (!EVP_DigestUpdate(mdctx, buf, sizeof(buf)))
  348. return 0;
  349. } while (t < end);
  350. if (!EVP_DigestUpdate(mdctx, key->rho, ML_KEM_RANDOM_BYTES))
  351. return 0;
  352. return EVP_DigestFinal_ex(mdctx, pkhash, &sz)
  353. && ossl_assert(sz == ML_KEM_PKHASH_BYTES);
  354. }
  355. /*
  356. * FIPS 203, Section 4.1, equation (4.5): G. SHA3-512 hash of a variable
  357. * length input, producing 64 bytes of output, in particular the seeds
  358. * (d,z) for key generation.
  359. */
  360. static __owur
  361. int hash_g(uint8_t out[ML_KEM_SEED_BYTES], const uint8_t *in, size_t len,
  362. EVP_MD_CTX *mdctx, const ML_KEM_KEY *key)
  363. {
  364. return EVP_DigestInit_ex(mdctx, key->sha3_512_md, NULL)
  365. && single_keccak(out, ML_KEM_SEED_BYTES, in, len, mdctx);
  366. }
  367. /*
  368. * FIPS 203, Section 4.1, equation (4.4): J. SHAKE256 taking a variable length
  369. * input to compute a 32-byte implicit rejection shared secret, of the same
  370. * length as the expected shared secret. (Computed even on success to avoid
  371. * side-channel leaks).
  372. */
  373. static __owur
  374. int kdf(uint8_t out[ML_KEM_SHARED_SECRET_BYTES],
  375. const uint8_t z[ML_KEM_RANDOM_BYTES],
  376. const uint8_t *ctext, size_t len,
  377. EVP_MD_CTX *mdctx, const ML_KEM_KEY *key)
  378. {
  379. return EVP_DigestInit_ex(mdctx, key->shake256_md, NULL)
  380. && EVP_DigestUpdate(mdctx, z, ML_KEM_RANDOM_BYTES)
  381. && EVP_DigestUpdate(mdctx, ctext, len)
  382. && EVP_DigestFinalXOF(mdctx, out, ML_KEM_SHARED_SECRET_BYTES);
  383. }
  384. /*
  385. * FIPS 203, Section 4.2.2, Algorithm 7: "SampleNTT" (steps 3-17, steps 1, 2
  386. * are performed by the caller). Rejection-samples a Keccak stream to get
  387. * uniformly distributed elements in the range [0,q). This is used for matrix
  388. * expansion and only operates on public inputs.
  389. */
  390. static __owur
  391. int sample_scalar(scalar *out, EVP_MD_CTX *mdctx)
  392. {
  393. uint16_t *curr = out->c, *endout = curr + DEGREE;
  394. uint8_t buf[SCALAR_SAMPLING_BUFSIZE], *in;
  395. uint8_t *endin = buf + sizeof(buf);
  396. uint16_t d;
  397. uint8_t b1, b2, b3;
  398. do {
  399. if (!EVP_DigestSqueeze(mdctx, in = buf, sizeof(buf)))
  400. return 0;
  401. do {
  402. b1 = *in++;
  403. b2 = *in++;
  404. b3 = *in++;
  405. if (curr >= endout)
  406. break;
  407. if ((d = ((b2 & 0x0f) << 8) + b1) < kPrime)
  408. *curr++ = d;
  409. if (curr >= endout)
  410. break;
  411. if ((d = (b3 << 4) + (b2 >> 4)) < kPrime)
  412. *curr++ = d;
  413. } while (in < endin);
  414. } while (curr < endout);
  415. return 1;
  416. }
  417. /*-
  418. * reduce_once reduces 0 <= x < 2*kPrime, mod kPrime.
  419. *
  420. * Subtract |q| if the input is larger, without exposing a side-channel,
  421. * avoiding the "clangover" attack. See |constish_time_non_zero| for a
  422. * discussion on why the value barrier is by default omitted.
  423. */
  424. static __owur uint16_t reduce_once(uint16_t x)
  425. {
  426. const uint16_t subtracted = x - kPrime;
  427. uint16_t mask = constish_time_non_zero(subtracted >> 15);
  428. return (mask & x) | (~mask & subtracted);
  429. }
  430. /*
  431. * Constant-time reduce x mod kPrime using Barrett reduction. x must be less
  432. * than kPrime + 2 * kPrime^2. This is sufficient to reduce a product of
  433. * two already reduced u_int16 values, in fact it is sufficient for each
  434. * to be less than 2^12, because (kPrime * (2 * kPrime + 1)) > 2^24.
  435. */
  436. static __owur uint16_t reduce(uint32_t x)
  437. {
  438. uint64_t product = (uint64_t)x * kBarrettMultiplier;
  439. uint32_t quotient = (uint32_t)(product >> kBarrettShift);
  440. uint32_t remainder = x - quotient * kPrime;
  441. return reduce_once(remainder);
  442. }
  443. /* Multiply a scalar by a constant. */
  444. static void scalar_mult_const(scalar *s, uint16_t a)
  445. {
  446. uint16_t *curr = s->c, *end = curr + DEGREE, tmp;
  447. do {
  448. tmp = reduce(*curr * a);
  449. *curr++ = tmp;
  450. } while (curr < end);
  451. }
  452. /*-
  453. * FIPS 203, Section 4.3, Algoritm 9: "NTT".
  454. * In-place number theoretic transform of a given scalar. Note that ML-KEM's
  455. * kPrime 3329 does not have a 512th root of unity, so this transform leaves
  456. * off the last iteration of the usual FFT code, with the 128 relevant roots of
  457. * unity being stored in NTTRoots. This means the output should be seen as 128
  458. * elements in GF(3329^2), with the coefficients of the elements being
  459. * consecutive entries in |s->c|.
  460. */
  461. static void scalar_ntt(scalar *s)
  462. {
  463. const uint16_t *roots = kNTTRoots;
  464. uint16_t *end = s->c + DEGREE;
  465. int offset = DEGREE / 2;
  466. do {
  467. uint16_t *curr = s->c, *peer;
  468. do {
  469. uint16_t *pause = curr + offset, even, odd;
  470. uint32_t zeta = *++roots;
  471. peer = pause;
  472. do {
  473. even = *curr;
  474. odd = reduce(*peer * zeta);
  475. *peer++ = reduce_once(even - odd + kPrime);
  476. *curr++ = reduce_once(odd + even);
  477. } while (curr < pause);
  478. } while ((curr = peer) < end);
  479. } while ((offset >>= 1) >= 2);
  480. }
  481. /*-
  482. * FIPS 203, Section 4.3, Algoritm 10: "NTT^(-1)".
  483. * In-place inverse number theoretic transform of a given scalar, with pairs of
  484. * entries of s->v being interpreted as elements of GF(3329^2). Just as with
  485. * the number theoretic transform, this leaves off the first step of the normal
  486. * iFFT to account for the fact that 3329 does not have a 512th root of unity,
  487. * using the precomputed 128 roots of unity stored in InverseNTTRoots.
  488. */
  489. static void scalar_inverse_ntt(scalar *s)
  490. {
  491. const uint16_t *roots = kInverseNTTRoots;
  492. uint16_t *end = s->c + DEGREE;
  493. int offset = 2;
  494. do {
  495. uint16_t *curr = s->c, *peer;
  496. do {
  497. uint16_t *pause = curr + offset, even, odd;
  498. uint32_t zeta = *++roots;
  499. peer = pause;
  500. do {
  501. even = *curr;
  502. odd = *peer;
  503. *peer++ = reduce(zeta * (even - odd + kPrime));
  504. *curr++ = reduce_once(odd + even);
  505. } while (curr < pause);
  506. } while ((curr = peer) < end);
  507. } while ((offset <<= 1) < DEGREE);
  508. scalar_mult_const(s, kInverseDegree);
  509. }
  510. /* Addition updating the LHS scalar in-place. */
  511. static void scalar_add(scalar *lhs, const scalar *rhs)
  512. {
  513. int i;
  514. for (i = 0; i < DEGREE; i++)
  515. lhs->c[i] = reduce_once(lhs->c[i] + rhs->c[i]);
  516. }
  517. /* Subtraction updating the LHS scalar in-place. */
  518. static void scalar_sub(scalar *lhs, const scalar *rhs)
  519. {
  520. int i;
  521. for (i = 0; i < DEGREE; i++)
  522. lhs->c[i] = reduce_once(lhs->c[i] - rhs->c[i] + kPrime);
  523. }
  524. /*
  525. * Multiplying two scalars in the number theoretically transformed state. Since
  526. * 3329 does not have a 512th root of unity, this means we have to interpret
  527. * the 2*ith and (2*i+1)th entries of the scalar as elements of
  528. * GF(3329)[X]/(X^2 - 17^(2*bitreverse(i)+1)).
  529. *
  530. * The value of 17^(2*bitreverse(i)+1) mod 3329 is stored in the precomputed
  531. * ModRoots table. Note that our Barrett transform only allows us to multipy
  532. * two reduced numbers together, so we need some intermediate reduction steps,
  533. * even if an uint64_t could hold 3 multiplied numbers.
  534. */
  535. static void scalar_mult(scalar *out, const scalar *lhs,
  536. const scalar *rhs)
  537. {
  538. uint16_t *curr = out->c, *end = curr + DEGREE;
  539. const uint16_t *lc = lhs->c, *rc = rhs->c;
  540. const uint16_t *roots = kModRoots;
  541. do {
  542. uint32_t l0 = *lc++, r0 = *rc++;
  543. uint32_t l1 = *lc++, r1 = *rc++;
  544. uint32_t zetapow = *roots++;
  545. *curr++ = reduce(l0 * r0 + reduce(l1 * r1) * zetapow);
  546. *curr++ = reduce(l0 * r1 + l1 * r0);
  547. } while (curr < end);
  548. }
  549. /* Above, but add the result to an existing scalar */
  550. static ossl_inline
  551. void scalar_mult_add(scalar *out, const scalar *lhs,
  552. const scalar *rhs)
  553. {
  554. uint16_t *curr = out->c, *end = curr + DEGREE;
  555. const uint16_t *lc = lhs->c, *rc = rhs->c;
  556. const uint16_t *roots = kModRoots;
  557. do {
  558. uint32_t l0 = *lc++, r0 = *rc++;
  559. uint32_t l1 = *lc++, r1 = *rc++;
  560. uint16_t *c0 = curr++;
  561. uint16_t *c1 = curr++;
  562. uint32_t zetapow = *roots++;
  563. *c0 = reduce(*c0 + l0 * r0 + reduce(l1 * r1) * zetapow);
  564. *c1 = reduce(*c1 + l0 * r1 + l1 * r0);
  565. } while (curr < end);
  566. }
  567. /*-
  568. * FIPS 203, Section 4.2.1, Algorithm 5: "ByteEncode_d", for 2<=d<=12.
  569. * Here |bits| is |d|. For efficiency, we handle the d=1 case separately.
  570. */
  571. static void scalar_encode(uint8_t *out, const scalar *s, int bits)
  572. {
  573. const uint16_t *curr = s->c, *end = curr + DEGREE;
  574. uint64_t accum = 0, element;
  575. int used = 0;
  576. do {
  577. element = *curr++;
  578. if (used + bits < 64) {
  579. accum |= element << used;
  580. used += bits;
  581. } else if (used + bits > 64) {
  582. out = OPENSSL_store_u64_le(out, accum | (element << used));
  583. accum = element >> (64 - used);
  584. used = (used + bits) - 64;
  585. } else {
  586. out = OPENSSL_store_u64_le(out, accum | (element << used));
  587. accum = 0;
  588. used = 0;
  589. }
  590. } while (curr < end);
  591. }
  592. /*
  593. * scalar_encode_1 is |scalar_encode| specialised for |bits| == 1.
  594. */
  595. static void scalar_encode_1(uint8_t out[DEGREE / 8], const scalar *s)
  596. {
  597. int i, j;
  598. uint8_t out_byte;
  599. for (i = 0; i < DEGREE; i += 8) {
  600. out_byte = 0;
  601. for (j = 0; j < 8; j++)
  602. out_byte |= bit0(s->c[i + j]) << j;
  603. *out = out_byte;
  604. out++;
  605. }
  606. }
  607. /*-
  608. * FIPS 203, Section 4.2.1, Algorithm 6: "ByteDecode_d", for 2<=d<12.
  609. * Here |bits| is |d|. For efficiency, we handle the d=1 and d=12 cases
  610. * separately.
  611. *
  612. * scalar_decode parses |DEGREE * bits| bits from |in| into |DEGREE| values in
  613. * |out|.
  614. */
  615. static void scalar_decode(scalar *out, const uint8_t *in, int bits)
  616. {
  617. uint16_t *curr = out->c, *end = curr + DEGREE;
  618. uint64_t accum = 0;
  619. int accum_bits = 0, todo = bits;
  620. uint16_t bitmask = (((uint16_t) 1) << bits) - 1, mask = bitmask;
  621. uint16_t element = 0;
  622. do {
  623. if (accum_bits == 0) {
  624. in = OPENSSL_load_u64_le(&accum, in);
  625. accum_bits = 64;
  626. }
  627. if (todo == bits && accum_bits >= bits) {
  628. /* No partial "element", and all the required bits available */
  629. *curr++ = ((uint16_t) accum) & mask;
  630. accum >>= bits;
  631. accum_bits -= bits;
  632. } else if (accum_bits >= todo) {
  633. /* A partial "element", and all the required bits available */
  634. *curr++ = element | ((((uint16_t) accum) & mask) << (bits - todo));
  635. accum >>= todo;
  636. accum_bits -= todo;
  637. element = 0;
  638. todo = bits;
  639. mask = bitmask;
  640. } else {
  641. /*
  642. * Only some of the requisite bits accumulated, store |accum_bits|
  643. * of these in |element|. The accumulated bitcount becomes 0, but
  644. * as soon as we have more bits we'll want to merge accum_bits
  645. * fewer of them into the final |element|.
  646. *
  647. * Note that with a 64-bit accumulator and |bits| always 12 or
  648. * less, if we're here, the previous iteration had all the
  649. * requisite bits, and so there are no kept bits in |element|.
  650. */
  651. element = ((uint16_t) accum) & mask;
  652. todo -= accum_bits;
  653. mask = bitmask >> accum_bits;
  654. accum_bits = 0;
  655. }
  656. } while (curr < end);
  657. }
  658. static __owur
  659. int scalar_decode_12(scalar *out, const uint8_t in[3 * DEGREE / 2])
  660. {
  661. int i;
  662. uint16_t *c = out->c;
  663. for (i = 0; i < DEGREE / 2; ++i) {
  664. uint8_t b1 = *in++;
  665. uint8_t b2 = *in++;
  666. uint8_t b3 = *in++;
  667. int outOfRange1 = (*c++ = b1 | ((b2 & 0x0f) << 8)) >= kPrime;
  668. int outOfRange2 = (*c++ = (b2 >> 4) | (b3 << 4)) >= kPrime;
  669. if (outOfRange1 | outOfRange2)
  670. return 0;
  671. }
  672. return 1;
  673. }
  674. /*-
  675. * scalar_decode_decompress_add is a combination of decoding and decompression
  676. * both specialised for |bits| == 1, with the result added (and sum reduced) to
  677. * the output scalar.
  678. *
  679. * NOTE: this function MUST not leak an input-data-depedennt timing signal.
  680. * A timing leak in a related function in the reference Kyber implementation
  681. * made the "clangover" attack (CVE-2024-37880) possible, giving key recovery
  682. * for ML-KEM-512 in minutes, provided the attacker has access to precise
  683. * timing of a CPU performing chosen-ciphertext decap. Admittedly this is only
  684. * a risk when private keys are reused (perhaps KEMTLS servers).
  685. */
  686. static void
  687. scalar_decode_decompress_add(scalar *out, const uint8_t in[DEGREE / 8])
  688. {
  689. static const uint16_t half_q_plus_1 = (ML_KEM_PRIME >> 1) + 1;
  690. uint16_t *curr = out->c, *end = curr + DEGREE;
  691. uint16_t mask;
  692. uint8_t b;
  693. /*
  694. * Add |half_q_plus_1| if the bit is set, without exposing a side-channel,
  695. * avoiding the "clangover" attack. See |constish_time_non_zero| for a
  696. * discussion on why the value barrier is by default omitted.
  697. */
  698. #define decode_decompress_add_bit \
  699. mask = constish_time_non_zero(bit0(b)); \
  700. *curr = reduce_once(*curr + (mask & half_q_plus_1)); \
  701. curr++; \
  702. b >>= 1
  703. /* Unrolled to process each byte in one iteration */
  704. do {
  705. b = *in++;
  706. decode_decompress_add_bit;
  707. decode_decompress_add_bit;
  708. decode_decompress_add_bit;
  709. decode_decompress_add_bit;
  710. decode_decompress_add_bit;
  711. decode_decompress_add_bit;
  712. decode_decompress_add_bit;
  713. decode_decompress_add_bit;
  714. } while (curr < end);
  715. #undef decode_decompress_add_bit
  716. }
  717. /*
  718. * FIPS 203, Section 4.2.1, Equation (4.7): Compress_d.
  719. *
  720. * Compresses (lossily) an input |x| mod 3329 into |bits| many bits by grouping
  721. * numbers close to each other together. The formula used is
  722. * round(2^|bits|/kPrime*x) mod 2^|bits|.
  723. * Uses Barrett reduction to achieve constant time. Since we need both the
  724. * remainder (for rounding) and the quotient (as the result), we cannot use
  725. * |reduce| here, but need to do the Barrett reduction directly.
  726. */
  727. static __owur uint16_t compress(uint16_t x, int bits)
  728. {
  729. uint32_t shifted = (uint32_t)x << bits;
  730. uint64_t product = (uint64_t)shifted * kBarrettMultiplier;
  731. uint32_t quotient = (uint32_t)(product >> kBarrettShift);
  732. uint32_t remainder = shifted - quotient * kPrime;
  733. /*
  734. * Adjust the quotient to round correctly:
  735. * 0 <= remainder <= kHalfPrime round to 0
  736. * kHalfPrime < remainder <= kPrime + kHalfPrime round to 1
  737. * kPrime + kHalfPrime < remainder < 2 * kPrime round to 2
  738. */
  739. quotient += 1 & constant_time_lt_32(kHalfPrime, remainder);
  740. quotient += 1 & constant_time_lt_32(kPrime + kHalfPrime, remainder);
  741. return quotient & ((1 << bits) - 1);
  742. }
  743. /*
  744. * FIPS 203, Section 4.2.1, Equation (4.8): Decompress_d.
  745. * Decompresses |x| by using a close equi-distant representative. The formula
  746. * is round(kPrime/2^|bits|*x). Note that 2^|bits| being the divisor allows us
  747. * to implement this logic using only bit operations.
  748. */
  749. static __owur uint16_t decompress(uint16_t x, int bits)
  750. {
  751. uint32_t product = (uint32_t)x * kPrime;
  752. uint32_t power = 1 << bits;
  753. /* This is |product| % power, since |power| is a power of 2. */
  754. uint32_t remainder = product & (power - 1);
  755. /* This is |product| / power, since |power| is a power of 2. */
  756. uint32_t lower = product >> bits;
  757. /*
  758. * The rounding logic works since the first half of numbers mod |power|
  759. * have a 0 as first bit, and the second half has a 1 as first bit, since
  760. * |power| is a power of 2. As a 12 bit number, |remainder| is always
  761. * positive, so we will shift in 0s for a right shift.
  762. */
  763. return lower + (remainder >> (bits - 1));
  764. }
  765. /*-
  766. * FIPS 203, Section 4.2.1, Equation (4.7): "Compress_d".
  767. * In-place lossy rounding of scalars to 2^d bits.
  768. */
  769. static void scalar_compress(scalar *s, int bits)
  770. {
  771. int i;
  772. for (i = 0; i < DEGREE; i++)
  773. s->c[i] = compress(s->c[i], bits);
  774. }
  775. /*
  776. * FIPS 203, Section 4.2.1, Equation (4.8): "Decompress_d".
  777. * In-place approximate recovery of scalars from 2^d bit compression.
  778. */
  779. static void scalar_decompress(scalar *s, int bits)
  780. {
  781. int i;
  782. for (i = 0; i < DEGREE; i++)
  783. s->c[i] = decompress(s->c[i], bits);
  784. }
  785. /* Addition updating the LHS vector in-place. */
  786. static void vector_add(scalar *lhs, const scalar *rhs, int rank)
  787. {
  788. do {
  789. scalar_add(lhs++, rhs++);
  790. } while (--rank > 0);
  791. }
  792. /*
  793. * Encodes an entire vector into 32*|rank|*|bits| bytes. Note that since 256
  794. * (DEGREE) is divisible by 8, the individual vector entries will always fill a
  795. * whole number of bytes, so we do not need to worry about bit packing here.
  796. */
  797. static void vector_encode(uint8_t *out, const scalar *a, int bits, int rank)
  798. {
  799. int stride = bits * DEGREE / 8;
  800. for (; rank-- > 0; out += stride)
  801. scalar_encode(out, a++, bits);
  802. }
  803. /*
  804. * Decodes 32*|rank|*|bits| bytes from |in| into |out|. It returns early
  805. * if any parsed value is >= |ML_KEM_PRIME|. The resulting scalars are
  806. * then decompressed and transformed via the NTT.
  807. *
  808. * Note: Used only in decrypt_cpa(), which returns void and so does not check
  809. * the return value of this function. Side-channels are fine when the input
  810. * ciphertext to decap() is simply syntactically invalid.
  811. */
  812. static void
  813. vector_decode_decompress_ntt(scalar *out, const uint8_t *in, int bits, int rank)
  814. {
  815. int stride = bits * DEGREE / 8;
  816. for (; rank-- > 0; in += stride, ++out) {
  817. scalar_decode(out, in, bits);
  818. scalar_decompress(out, bits);
  819. scalar_ntt(out);
  820. }
  821. }
  822. /* vector_decode(), specialised to bits == 12. */
  823. static __owur
  824. int vector_decode_12(scalar *out, const uint8_t in[3 * DEGREE / 2], int rank)
  825. {
  826. int stride = 3 * DEGREE / 2;
  827. for (; rank-- > 0; in += stride)
  828. if (!scalar_decode_12(out++, in))
  829. return 0;
  830. return 1;
  831. }
  832. /* In-place compression of each scalar component */
  833. static void vector_compress(scalar *a, int bits, int rank)
  834. {
  835. do {
  836. scalar_compress(a++, bits);
  837. } while (--rank > 0);
  838. }
  839. /* The output scalar must not overlap with the inputs */
  840. static void inner_product(scalar *out, const scalar *lhs, const scalar *rhs,
  841. int rank)
  842. {
  843. scalar_mult(out, lhs, rhs);
  844. while (--rank > 0)
  845. scalar_mult_add(out, ++lhs, ++rhs);
  846. }
  847. /*
  848. * Here, the output vector must not overlap with the inputs, the result is
  849. * directly subjected to inverse NTT.
  850. */
  851. static void
  852. matrix_mult_intt(scalar *out, const scalar *m, const scalar *a, int rank)
  853. {
  854. const scalar *ar;
  855. int i, j;
  856. for (i = rank; i-- > 0; ++out) {
  857. scalar_mult(out, m++, ar = a);
  858. for (j = rank - 1; j > 0; --j)
  859. scalar_mult_add(out, m++, ++ar);
  860. scalar_inverse_ntt(out);
  861. }
  862. }
  863. /* Here, the output vector must not overlap with the inputs */
  864. static void
  865. matrix_mult_transpose_add(scalar *out, const scalar *m, const scalar *a, int rank)
  866. {
  867. const scalar *mc = m, *mr, *ar;
  868. int i, j;
  869. for (i = rank; i-- > 0; ++out) {
  870. scalar_mult_add(out, mr = mc++, ar = a);
  871. for (j = rank; --j > 0; )
  872. scalar_mult_add(out, (mr += rank), ++ar);
  873. }
  874. }
  875. /*-
  876. * Expands the matrix from a seed for key generation and for encaps-CPA.
  877. * NOTE: FIPS 203 matrix "A" is the transpose of this matrix, computed
  878. * by appending the (i,j) indices to the seed in the opposite order!
  879. *
  880. * Where FIPS 203 computes t = A * s + e, we use the transpose of "m".
  881. */
  882. static __owur
  883. int matrix_expand(EVP_MD_CTX *mdctx, ML_KEM_KEY *key)
  884. {
  885. scalar *out = key->m;
  886. uint8_t input[ML_KEM_RANDOM_BYTES + 2];
  887. int rank = key->vinfo->rank;
  888. int i, j;
  889. memcpy(input, key->rho, ML_KEM_RANDOM_BYTES);
  890. for (i = 0; i < rank; i++) {
  891. for (j = 0; j < rank; j++) {
  892. input[ML_KEM_RANDOM_BYTES] = i;
  893. input[ML_KEM_RANDOM_BYTES + 1] = j;
  894. if (!EVP_DigestInit_ex(mdctx, key->shake128_md, NULL)
  895. || !EVP_DigestUpdate(mdctx, input, sizeof(input))
  896. || !sample_scalar(out++, mdctx))
  897. return 0;
  898. }
  899. }
  900. return 1;
  901. }
  902. /*
  903. * Algorithm 7 from the spec, with eta fixed to two and the PRF call
  904. * included. Creates binominally distributed elements by sampling 2*|eta| bits,
  905. * and setting the coefficient to the count of the first bits minus the count of
  906. * the second bits, resulting in a centered binomial distribution. Since eta is
  907. * two this gives -2/2 with a probability of 1/16, -1/1 with probability 1/4,
  908. * and 0 with probability 3/8.
  909. */
  910. static __owur
  911. int cbd_2(scalar *out, uint8_t in[ML_KEM_RANDOM_BYTES + 1],
  912. EVP_MD_CTX *mdctx, const ML_KEM_KEY *key)
  913. {
  914. uint16_t *curr = out->c, *end = curr + DEGREE;
  915. uint8_t randbuf[4 * DEGREE / 8], *r = randbuf; /* 64 * eta slots */
  916. uint16_t value, mask;
  917. uint8_t b;
  918. if (!prf(randbuf, sizeof(randbuf), in, mdctx, key))
  919. return 0;
  920. do {
  921. b = *r++;
  922. /*
  923. * Add |kPrime| if |value| underflowed. See |constish_time_non_zero|
  924. * for a discussion on why the value barrier is by default omitted.
  925. * While this could have been written reduce_once(value + kPrime), this
  926. * is one extra addition and small range of |value| tempts some
  927. * versions of Clang to emit a branch.
  928. */
  929. value = bit0(b) + bitn(1, b);
  930. value -= bitn(2, b) + bitn(3, b);
  931. mask = constish_time_non_zero(value >> 15);
  932. *curr++ = value + (kPrime & mask);
  933. value = bitn(4, b) + bitn(5, b);
  934. value -= bitn(6, b) + bitn(7, b);
  935. mask = constish_time_non_zero(value >> 15);
  936. *curr++ = value + (kPrime & mask);
  937. } while (curr < end);
  938. return 1;
  939. }
  940. /*
  941. * Algorithm 7 from the spec, with eta fixed to three and the PRF call
  942. * included. Creates binominally distributed elements by sampling 3*|eta| bits,
  943. * and setting the coefficient to the count of the first bits minus the count of
  944. * the second bits, resulting in a centered binomial distribution.
  945. */
  946. static __owur
  947. int cbd_3(scalar *out, uint8_t in[ML_KEM_RANDOM_BYTES + 1],
  948. EVP_MD_CTX *mdctx, const ML_KEM_KEY *key)
  949. {
  950. uint16_t *curr = out->c, *end = curr + DEGREE;
  951. uint8_t randbuf[6 * DEGREE / 8], *r = randbuf; /* 64 * eta slots */
  952. uint8_t b1, b2, b3;
  953. uint16_t value, mask;
  954. if (!prf(randbuf, sizeof(randbuf), in, mdctx, key))
  955. return 0;
  956. do {
  957. b1 = *r++;
  958. b2 = *r++;
  959. b3 = *r++;
  960. /*
  961. * Add |kPrime| if |value| underflowed. See |constish_time_non_zero|
  962. * for a discussion on why the value barrier is by default omitted.
  963. * While this could have been written reduce_once(value + kPrime), this
  964. * is one extra addition and small range of |value| tempts some
  965. * versions of Clang to emit a branch.
  966. */
  967. value = bit0(b1) + bitn(1, b1) + bitn(2, b1);
  968. value -= bitn(3, b1) + bitn(4, b1) + bitn(5, b1);
  969. mask = constish_time_non_zero(value >> 15);
  970. *curr++ = value + (kPrime & mask);
  971. value = bitn(6, b1) + bitn(7, b1) + bit0(b2);
  972. value -= bitn(1, b2) + bitn(2, b2) + bitn(3, b2);
  973. mask = constish_time_non_zero(value >> 15);
  974. *curr++ = value + (kPrime & mask);
  975. value = bitn(4, b2) + bitn(5, b2) + bitn(6, b2);
  976. value -= bitn(7, b2) + bit0(b3) + bitn(1, b3);
  977. mask = constish_time_non_zero(value >> 15);
  978. *curr++ = value + (kPrime & mask);
  979. value = bitn(2, b3) + bitn(3, b3) + bitn(4, b3);
  980. value -= bitn(5, b3) + bitn(6, b3) + bitn(7, b3);
  981. mask = constish_time_non_zero(value >> 15);
  982. *curr++ = value + (kPrime & mask);
  983. } while (curr < end);
  984. return 1;
  985. }
  986. /*
  987. * Generates a secret vector by using |cbd| with the given seed to generate
  988. * scalar elements and incrementing |counter| for each slot of the vector.
  989. */
  990. static __owur
  991. int gencbd_vector(scalar *out, CBD_FUNC cbd, uint8_t *counter,
  992. const uint8_t seed[ML_KEM_RANDOM_BYTES], int rank,
  993. EVP_MD_CTX *mdctx, const ML_KEM_KEY *key)
  994. {
  995. uint8_t input[ML_KEM_RANDOM_BYTES + 1];
  996. memcpy(input, seed, ML_KEM_RANDOM_BYTES);
  997. do {
  998. input[ML_KEM_RANDOM_BYTES] = (*counter)++;
  999. if (!cbd(out++, input, mdctx, key))
  1000. return 0;
  1001. } while (--rank > 0);
  1002. return 1;
  1003. }
  1004. /*
  1005. * As above plus NTT transform.
  1006. */
  1007. static __owur
  1008. int gencbd_vector_ntt(scalar *out, CBD_FUNC cbd, uint8_t *counter,
  1009. const uint8_t seed[ML_KEM_RANDOM_BYTES], int rank,
  1010. EVP_MD_CTX *mdctx, const ML_KEM_KEY *key)
  1011. {
  1012. uint8_t input[ML_KEM_RANDOM_BYTES + 1];
  1013. memcpy(input, seed, ML_KEM_RANDOM_BYTES);
  1014. do {
  1015. input[ML_KEM_RANDOM_BYTES] = (*counter)++;
  1016. if (!cbd(out, input, mdctx, key))
  1017. return 0;
  1018. scalar_ntt(out++);
  1019. } while (--rank > 0);
  1020. return 1;
  1021. }
  1022. /* The |ETA1| value for ML-KEM-512 is 3, the rest and all ETA2 values are 2. */
  1023. #define CBD1(evp_type) ((evp_type) == EVP_PKEY_ML_KEM_512 ? cbd_3 : cbd_2)
  1024. /*
  1025. * FIPS 203, Section 5.2, Algorithm 14: K-PKE.Encrypt.
  1026. *
  1027. * Encrypts a message with given randomness to the ciphertext in |out|. Without
  1028. * applying the Fujisaki-Okamoto transform this would not result in a CCA
  1029. * secure scheme, since lattice schemes are vulnerable to decryption failure
  1030. * oracles.
  1031. *
  1032. * The steps are re-ordered to make more efficient/localised use of storage.
  1033. *
  1034. * Note also that the input public key is assumed to hold a precomputed matrix
  1035. * |A| (our key->m, with the public key holding an expanded (16-bit per scalar
  1036. * coefficient) key->t vector).
  1037. *
  1038. * Caller passes storage in |tmp| for for two temporary vectors.
  1039. */
  1040. static __owur
  1041. int encrypt_cpa(uint8_t out[ML_KEM_SHARED_SECRET_BYTES],
  1042. const uint8_t message[DEGREE / 8],
  1043. const uint8_t r[ML_KEM_RANDOM_BYTES], scalar *tmp,
  1044. EVP_MD_CTX *mdctx, const ML_KEM_KEY *key)
  1045. {
  1046. const ML_KEM_VINFO *vinfo = key->vinfo;
  1047. CBD_FUNC cbd_1 = CBD1(vinfo->evp_type);
  1048. int rank = vinfo->rank;
  1049. /* We can use tmp[0..rank-1] as storage for |y|, then |e1|, ... */
  1050. scalar *y = &tmp[0], *e1 = y, *e2 = y;
  1051. /* We can use tmp[rank]..tmp[2*rank - 1] for |u| */
  1052. scalar *u = &tmp[rank];
  1053. scalar v;
  1054. uint8_t input[ML_KEM_RANDOM_BYTES + 1];
  1055. uint8_t counter = 0;
  1056. int du = vinfo->du;
  1057. int dv = vinfo->dv;
  1058. /* FIPS 203 "y" vector */
  1059. if (!gencbd_vector_ntt(y, cbd_1, &counter, r, rank, mdctx, key))
  1060. return 0;
  1061. /* FIPS 203 "v" scalar */
  1062. inner_product(&v, key->t, y, rank);
  1063. scalar_inverse_ntt(&v);
  1064. /* FIPS 203 "u" vector */
  1065. matrix_mult_intt(u, key->m, y, rank);
  1066. /* All done with |y|, now free to reuse tmp[0] for FIPS 203 |e1| */
  1067. if (!gencbd_vector(e1, cbd_2, &counter, r, rank, mdctx, key))
  1068. return 0;
  1069. vector_add(u, e1, rank);
  1070. vector_compress(u, du, rank);
  1071. vector_encode(out, u, du, rank);
  1072. /* All done with |e1|, now free to reuse tmp[0] for FIPS 203 |e2| */
  1073. memcpy(input, r, ML_KEM_RANDOM_BYTES);
  1074. input[ML_KEM_RANDOM_BYTES] = counter;
  1075. if (!cbd_2(e2, input, mdctx, key))
  1076. return 0;
  1077. scalar_add(&v, e2);
  1078. /* Combine message with |v| */
  1079. scalar_decode_decompress_add(&v, message);
  1080. scalar_compress(&v, dv);
  1081. scalar_encode(out + vinfo->u_vector_bytes, &v, dv);
  1082. return 1;
  1083. }
  1084. /*
  1085. * FIPS 203, Section 5.3, Algorithm 15: K-PKE.Decrypt.
  1086. */
  1087. static void
  1088. decrypt_cpa(uint8_t out[ML_KEM_SHARED_SECRET_BYTES],
  1089. const uint8_t *ctext, scalar *u, const ML_KEM_KEY *key)
  1090. {
  1091. const ML_KEM_VINFO *vinfo = key->vinfo;
  1092. scalar v, mask;
  1093. int rank = vinfo->rank;
  1094. int du = vinfo->du;
  1095. int dv = vinfo->dv;
  1096. vector_decode_decompress_ntt(u, ctext, du, rank);
  1097. scalar_decode(&v, ctext + vinfo->u_vector_bytes, dv);
  1098. scalar_decompress(&v, dv);
  1099. inner_product(&mask, key->s, u, rank);
  1100. scalar_inverse_ntt(&mask);
  1101. scalar_sub(&v, &mask);
  1102. scalar_compress(&v, 1);
  1103. scalar_encode_1(out, &v);
  1104. }
  1105. /*-
  1106. * FIPS 203, Section 7.1, Algorithm 19: "ML-KEM.KeyGen".
  1107. * FIPS 203, Section 7.2, Algorithm 20: "ML-KEM.Encaps".
  1108. *
  1109. * Fills the |out| buffer with the |ek| output of "ML-KEM.KeyGen", or,
  1110. * equivalently, the |ek| input of "ML-KEM.Encaps", i.e. returns the
  1111. * wire-format of an ML-KEM public key.
  1112. */
  1113. static void encode_pubkey(uint8_t *out, const ML_KEM_KEY *key)
  1114. {
  1115. const uint8_t *rho = key->rho;
  1116. const ML_KEM_VINFO *vinfo = key->vinfo;
  1117. vector_encode(out, key->t, 12, vinfo->rank);
  1118. memcpy(out + vinfo->vector_bytes, rho, ML_KEM_RANDOM_BYTES);
  1119. }
  1120. /*-
  1121. * FIPS 203, Section 7.1, Algorithm 19: "ML-KEM.KeyGen".
  1122. *
  1123. * Fills the |out| buffer with the |dk| output of "ML-KEM.KeyGen".
  1124. * This matches the input format of parse_prvkey() below.
  1125. */
  1126. static void encode_prvkey(uint8_t *out, const ML_KEM_KEY *key)
  1127. {
  1128. const ML_KEM_VINFO *vinfo = key->vinfo;
  1129. vector_encode(out, key->s, 12, vinfo->rank);
  1130. out += vinfo->vector_bytes;
  1131. encode_pubkey(out, key);
  1132. out += vinfo->pubkey_bytes;
  1133. memcpy(out, key->pkhash, ML_KEM_PKHASH_BYTES);
  1134. out += ML_KEM_PKHASH_BYTES;
  1135. memcpy(out, key->z, ML_KEM_RANDOM_BYTES);
  1136. }
  1137. /*-
  1138. * FIPS 203, Section 7.1, Algorithm 19: "ML-KEM.KeyGen".
  1139. * FIPS 203, Section 7.2, Algorithm 20: "ML-KEM.Encaps".
  1140. *
  1141. * This function parses the |in| buffer as the |ek| output of "ML-KEM.KeyGen",
  1142. * or, equivalently, the |ek| input of "ML-KEM.Encaps", i.e. decodes the
  1143. * wire-format of the ML-KEM public key.
  1144. */
  1145. static int parse_pubkey(const uint8_t *in, EVP_MD_CTX *mdctx, ML_KEM_KEY *key)
  1146. {
  1147. const ML_KEM_VINFO *vinfo = key->vinfo;
  1148. /* Decode and check |t| */
  1149. if (!vector_decode_12(key->t, in, vinfo->rank)) {
  1150. ERR_raise_data(ERR_LIB_PROV, PROV_R_INVALID_KEY,
  1151. "%s invalid public 't' vector",
  1152. vinfo->algorithm_name);
  1153. return 0;
  1154. }
  1155. /* Save the matrix |m| recovery seed |rho| */
  1156. memcpy(key->rho, in + vinfo->vector_bytes, ML_KEM_RANDOM_BYTES);
  1157. /*
  1158. * Pre-compute the public key hash, needed for both encap and decap.
  1159. * Also pre-compute the matrix expansion, stored with the public key.
  1160. */
  1161. if (!hash_h(key->pkhash, in, vinfo->pubkey_bytes, mdctx, key)
  1162. || !matrix_expand(mdctx, key)) {
  1163. ERR_raise_data(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR,
  1164. "internal error while parsing %s public key",
  1165. vinfo->algorithm_name);
  1166. return 0;
  1167. }
  1168. return 1;
  1169. }
  1170. /*
  1171. * FIPS 203, Section 7.1, Algorithm 19: "ML-KEM.KeyGen".
  1172. *
  1173. * Parses the |in| buffer as a |dk| output of "ML-KEM.KeyGen".
  1174. * This matches the output format of encode_prvkey() above.
  1175. */
  1176. static int parse_prvkey(const uint8_t *in, EVP_MD_CTX *mdctx, ML_KEM_KEY *key)
  1177. {
  1178. const ML_KEM_VINFO *vinfo = key->vinfo;
  1179. /* Decode and check |s|. */
  1180. if (!vector_decode_12(key->s, in, vinfo->rank)) {
  1181. ERR_raise_data(ERR_LIB_PROV, PROV_R_INVALID_KEY,
  1182. "%s invalid private 's' vector",
  1183. vinfo->algorithm_name);
  1184. return 0;
  1185. }
  1186. in += vinfo->vector_bytes;
  1187. if (!parse_pubkey(in, mdctx, key))
  1188. return 0;
  1189. in += vinfo->pubkey_bytes;
  1190. /* Check public key hash. */
  1191. if (memcmp(key->pkhash, in, ML_KEM_PKHASH_BYTES) != 0) {
  1192. ERR_raise_data(ERR_LIB_PROV, PROV_R_INVALID_KEY,
  1193. "%s public key hash mismatch",
  1194. vinfo->algorithm_name);
  1195. return 0;
  1196. }
  1197. in += ML_KEM_PKHASH_BYTES;
  1198. memcpy(key->z, in, ML_KEM_RANDOM_BYTES);
  1199. return 1;
  1200. }
  1201. /*
  1202. * FIPS 203, Section 6.1, Algorithm 16: "ML-KEM.KeyGen_internal".
  1203. *
  1204. * The implementation of Section 5.1, Algorithm 13, "K-PKE.KeyGen(d)" is
  1205. * inlined.
  1206. *
  1207. * The caller MUST pass a pre-allocated digest context that is not shared with
  1208. * any concurrent computation.
  1209. *
  1210. * This function optionally outputs the serialised wire-form |ek| public key
  1211. * into the provided |pubenc| buffer, and generates the content of the |rho|,
  1212. * |pkhash|, |t|, |m|, |s| and |z| components of the private |key| (which must
  1213. * have preallocated space for these).
  1214. *
  1215. * Keys are computed from a 32-byte random |d| plus the 1 byte rank for
  1216. * domain separation. These are concatenated and hashed to produce a pair of
  1217. * 32-byte seeds public "rho", used to generate the matrix, and private "sigma",
  1218. * used to generate the secret vector |s|.
  1219. *
  1220. * The second random input |z| is copied verbatim into the Fujisaki-Okamoto
  1221. * (FO) transform "implicit-rejection" secret (the |z| component of the private
  1222. * key), which thwarts chosen-ciphertext attacks, provided decap() runs in
  1223. * constant time, with no side channel leaks, on all well-formed (valid length,
  1224. * and correctly encoded) ciphertext inputs.
  1225. */
  1226. static __owur
  1227. int genkey(const uint8_t seed[ML_KEM_SEED_BYTES],
  1228. EVP_MD_CTX *mdctx, uint8_t *pubenc, ML_KEM_KEY *key)
  1229. {
  1230. uint8_t hashed[2 * ML_KEM_RANDOM_BYTES];
  1231. const uint8_t *const sigma = hashed + ML_KEM_RANDOM_BYTES;
  1232. uint8_t augmented_seed[ML_KEM_RANDOM_BYTES + 1];
  1233. const ML_KEM_VINFO *vinfo = key->vinfo;
  1234. CBD_FUNC cbd_1 = CBD1(vinfo->evp_type);
  1235. int rank = vinfo->rank;
  1236. uint8_t counter = 0;
  1237. int ret = 0;
  1238. /*
  1239. * Use the "d" seed salted with the rank to derive the public and private
  1240. * seeds rho and sigma.
  1241. */
  1242. memcpy(augmented_seed, seed, ML_KEM_RANDOM_BYTES);
  1243. augmented_seed[ML_KEM_RANDOM_BYTES] = (uint8_t) rank;
  1244. if (!hash_g(hashed, augmented_seed, sizeof(augmented_seed), mdctx, key))
  1245. goto end;
  1246. memcpy(key->rho, hashed, ML_KEM_RANDOM_BYTES);
  1247. /* The |rho| matrix seed is public */
  1248. CONSTTIME_DECLASSIFY(key->rho, ML_KEM_RANDOM_BYTES);
  1249. /* FIPS 203 |e| vector is initial value of key->t */
  1250. if (!matrix_expand(mdctx, key)
  1251. || !gencbd_vector_ntt(key->s, cbd_1, &counter, sigma, rank, mdctx, key)
  1252. || !gencbd_vector_ntt(key->t, cbd_1, &counter, sigma, rank, mdctx, key))
  1253. goto end;
  1254. /* To |e| we now add the product of transpose |m| and |s|, giving |t|. */
  1255. matrix_mult_transpose_add(key->t, key->m, key->s, rank);
  1256. /* The |t| vector is public */
  1257. CONSTTIME_DECLASSIFY(key->t, vinfo->rank * sizeof(scalar));
  1258. if (pubenc == NULL) {
  1259. /* Incremental digest of public key without in-full serialisation. */
  1260. if (!hash_h_pubkey(key->pkhash, mdctx, key))
  1261. goto end;
  1262. } else {
  1263. encode_pubkey(pubenc, key);
  1264. if (!hash_h(key->pkhash, pubenc, vinfo->pubkey_bytes, mdctx, key))
  1265. goto end;
  1266. }
  1267. /* Save |z| portion of seed for "implicit rejection" on failure. */
  1268. memcpy(key->z, seed + ML_KEM_RANDOM_BYTES, ML_KEM_RANDOM_BYTES);
  1269. /* Optionally save the |d| portion of the seed */
  1270. key->d = key->z + ML_KEM_RANDOM_BYTES;
  1271. if (key->prov_flags & ML_KEM_KEY_RETAIN_SEED) {
  1272. memcpy(key->d, seed, ML_KEM_RANDOM_BYTES);
  1273. } else {
  1274. OPENSSL_cleanse(key->d, ML_KEM_RANDOM_BYTES);
  1275. key->d = NULL;
  1276. }
  1277. ret = 1;
  1278. end:
  1279. OPENSSL_cleanse((void *)augmented_seed, ML_KEM_RANDOM_BYTES);
  1280. OPENSSL_cleanse((void *)sigma, ML_KEM_RANDOM_BYTES);
  1281. if (ret == 0) {
  1282. ERR_raise_data(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR,
  1283. "internal error while generating %s private key",
  1284. vinfo->algorithm_name);
  1285. }
  1286. return ret;
  1287. }
  1288. /*-
  1289. * FIPS 203, Section 6.2, Algorithm 17: "ML-KEM.Encaps_internal".
  1290. * This is the deterministic version with randomness supplied externally.
  1291. *
  1292. * The caller must pass space for two vectors in |tmp|.
  1293. * The |ctext| buffer have space for the ciphertext of the ML-KEM variant
  1294. * of the provided key.
  1295. */
  1296. static
  1297. int encap(uint8_t *ctext, uint8_t secret[ML_KEM_SHARED_SECRET_BYTES],
  1298. const uint8_t entropy[ML_KEM_RANDOM_BYTES],
  1299. scalar *tmp, EVP_MD_CTX *mdctx, const ML_KEM_KEY *key)
  1300. {
  1301. uint8_t input[ML_KEM_RANDOM_BYTES + ML_KEM_PKHASH_BYTES];
  1302. uint8_t Kr[ML_KEM_SHARED_SECRET_BYTES + ML_KEM_RANDOM_BYTES];
  1303. uint8_t *r = Kr + ML_KEM_SHARED_SECRET_BYTES;
  1304. int ret;
  1305. memcpy(input, entropy, ML_KEM_RANDOM_BYTES);
  1306. memcpy(input + ML_KEM_RANDOM_BYTES, key->pkhash, ML_KEM_PKHASH_BYTES);
  1307. ret = hash_g(Kr, input, sizeof(input), mdctx, key)
  1308. && encrypt_cpa(ctext, entropy, r, tmp, mdctx, key);
  1309. OPENSSL_cleanse((void *)input, sizeof(input));
  1310. if (ret)
  1311. memcpy(secret, Kr, ML_KEM_SHARED_SECRET_BYTES);
  1312. else
  1313. ERR_raise_data(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR,
  1314. "internal error while performing %s encapsulation",
  1315. key->vinfo->algorithm_name);
  1316. return ret;
  1317. }
  1318. /*
  1319. * FIPS 203, Section 6.3, Algorithm 18: ML-KEM.Decaps_internal
  1320. *
  1321. * Barring failure of the supporting SHA3/SHAKE primitives, this is fully
  1322. * deterministic, the randomness for the FO transform is extracted during
  1323. * private key generation.
  1324. *
  1325. * The caller must pass space for two vectors in |tmp|.
  1326. * The |ctext| and |tmp_ctext| buffers must each have space for the ciphertext
  1327. * of the key's ML-KEM variant.
  1328. */
  1329. static
  1330. int decap(uint8_t secret[ML_KEM_SHARED_SECRET_BYTES],
  1331. const uint8_t *ctext, uint8_t *tmp_ctext, scalar *tmp,
  1332. EVP_MD_CTX *mdctx, const ML_KEM_KEY *key)
  1333. {
  1334. uint8_t decrypted[ML_KEM_SHARED_SECRET_BYTES + ML_KEM_PKHASH_BYTES];
  1335. uint8_t failure_key[ML_KEM_RANDOM_BYTES];
  1336. uint8_t Kr[ML_KEM_SHARED_SECRET_BYTES + ML_KEM_RANDOM_BYTES];
  1337. uint8_t *r = Kr + ML_KEM_SHARED_SECRET_BYTES;
  1338. const uint8_t *pkhash = key->pkhash;
  1339. const ML_KEM_VINFO *vinfo = key->vinfo;
  1340. int i;
  1341. uint8_t mask;
  1342. /*
  1343. * If our KDF is unavailable, fail early! Otherwise, keep going ignoring
  1344. * any further errors, returning success, and whatever we got for a shared
  1345. * secret. The decrypt_cpa() function is just arithmetic on secret data,
  1346. * so should not be subject to failure that makes its output predictable.
  1347. *
  1348. * We guard against "should never happen" catastrophic failure of the
  1349. * "pure" function |hash_g| by overwriting the shared secret with the
  1350. * content of the failure key and returning early, if nevertheless hash_g
  1351. * fails. This is not constant-time, but a failure of |hash_g| already
  1352. * implies loss of side-channel resistance.
  1353. *
  1354. * The same action is taken, if also |encrypt_cpa| should catastrophically
  1355. * fail, due to failure of the |PRF| underlying the CBD functions.
  1356. */
  1357. if (!kdf(failure_key, key->z, ctext, vinfo->ctext_bytes, mdctx, key)) {
  1358. ERR_raise_data(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR,
  1359. "internal error while performing %s decapsulation",
  1360. vinfo->algorithm_name);
  1361. return 0;
  1362. }
  1363. decrypt_cpa(decrypted, ctext, tmp, key);
  1364. memcpy(decrypted + ML_KEM_SHARED_SECRET_BYTES, pkhash, ML_KEM_PKHASH_BYTES);
  1365. if (!hash_g(Kr, decrypted, sizeof(decrypted), mdctx, key)
  1366. || !encrypt_cpa(tmp_ctext, decrypted, r, tmp, mdctx, key)) {
  1367. memcpy(secret, failure_key, ML_KEM_SHARED_SECRET_BYTES);
  1368. OPENSSL_cleanse(decrypted, ML_KEM_SHARED_SECRET_BYTES);
  1369. return 1;
  1370. }
  1371. mask = constant_time_eq_int_8(0,
  1372. CRYPTO_memcmp(ctext, tmp_ctext, vinfo->ctext_bytes));
  1373. for (i = 0; i < ML_KEM_SHARED_SECRET_BYTES; i++)
  1374. secret[i] = constant_time_select_8(mask, Kr[i], failure_key[i]);
  1375. OPENSSL_cleanse(decrypted, ML_KEM_SHARED_SECRET_BYTES);
  1376. OPENSSL_cleanse(Kr, sizeof(Kr));
  1377. return 1;
  1378. }
  1379. /*
  1380. * After allocating storage for public or private key data, update the key
  1381. * component pointers to reference that storage.
  1382. */
  1383. static __owur
  1384. int add_storage(scalar *p, int private, ML_KEM_KEY *key)
  1385. {
  1386. int rank = key->vinfo->rank;
  1387. if (p == NULL)
  1388. return 0;
  1389. /*
  1390. * We're adding key material, the seed buffer will now hold |rho| and
  1391. * |pkhash|.
  1392. */
  1393. memset(key->seedbuf, 0, sizeof(key->seedbuf));
  1394. key->rho = key->seedbuf;
  1395. key->pkhash = key->seedbuf + ML_KEM_RANDOM_BYTES;
  1396. key->d = key->z = NULL;
  1397. /* A public key needs space for |t| and |m| */
  1398. key->m = (key->t = p) + rank;
  1399. /*
  1400. * A private key also needs space for |s| and |z|.
  1401. * The |z| buffer always includes additional space for |d|, but a key's |d|
  1402. * pointer is left NULL when parsed from the NIST format, which omits that
  1403. * information. Only keys generated from a (d, z) seed pair will have a
  1404. * non-NULL |d| pointer.
  1405. */
  1406. if (private)
  1407. key->z = (uint8_t *)(rank + (key->s = key->m + rank * rank));
  1408. return 1;
  1409. }
  1410. /*
  1411. * After freeing the storage associated with a key that failed to be
  1412. * constructed, reset the internal pointers back to NULL.
  1413. */
  1414. void
  1415. ossl_ml_kem_key_reset(ML_KEM_KEY *key)
  1416. {
  1417. if (key->t == NULL)
  1418. return;
  1419. /*-
  1420. * Cleanse any sensitive data:
  1421. * - The private vector |s| is immediately followed by the FO failure
  1422. * secret |z|, and seed |d|, we can cleanse all three in one call.
  1423. *
  1424. * - Otherwise, when key->d is set, cleanse the stashed seed.
  1425. */
  1426. if (ossl_ml_kem_have_prvkey(key))
  1427. OPENSSL_cleanse(key->s,
  1428. key->vinfo->rank * sizeof(scalar) + 2 * ML_KEM_RANDOM_BYTES);
  1429. OPENSSL_free(key->t);
  1430. key->d = key->z = (uint8_t *)(key->s = key->m = key->t = NULL);
  1431. }
  1432. /*
  1433. * ----- API exported to the provider
  1434. *
  1435. * Parameters with an implicit fixed length in the internal static API of each
  1436. * variant have an explicit checked length argument at this layer.
  1437. */
  1438. /* Retrieve the parameters of one of the ML-KEM variants */
  1439. const ML_KEM_VINFO *ossl_ml_kem_get_vinfo(int evp_type)
  1440. {
  1441. switch (evp_type) {
  1442. case EVP_PKEY_ML_KEM_512:
  1443. return &vinfo_map[ML_KEM_512_VINFO];
  1444. case EVP_PKEY_ML_KEM_768:
  1445. return &vinfo_map[ML_KEM_768_VINFO];
  1446. case EVP_PKEY_ML_KEM_1024:
  1447. return &vinfo_map[ML_KEM_1024_VINFO];
  1448. }
  1449. return NULL;
  1450. }
  1451. ML_KEM_KEY *ossl_ml_kem_key_new(OSSL_LIB_CTX *libctx, const char *properties,
  1452. int evp_type)
  1453. {
  1454. const ML_KEM_VINFO *vinfo = ossl_ml_kem_get_vinfo(evp_type);
  1455. ML_KEM_KEY *key;
  1456. if (vinfo == NULL) {
  1457. ERR_raise_data(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT,
  1458. "unsupported ML-KEM key type: %d", evp_type);
  1459. return NULL;
  1460. }
  1461. if ((key = OPENSSL_malloc(sizeof(*key))) == NULL)
  1462. return NULL;
  1463. key->vinfo = vinfo;
  1464. key->libctx = libctx;
  1465. key->prov_flags = ML_KEM_KEY_PROV_FLAGS_DEFAULT;
  1466. key->shake128_md = EVP_MD_fetch(libctx, "SHAKE128", properties);
  1467. key->shake256_md = EVP_MD_fetch(libctx, "SHAKE256", properties);
  1468. key->sha3_256_md = EVP_MD_fetch(libctx, "SHA3-256", properties);
  1469. key->sha3_512_md = EVP_MD_fetch(libctx, "SHA3-512", properties);
  1470. key->d = key->z = key->rho = key->pkhash = key->encoded_dk = NULL;
  1471. key->s = key->m = key->t = NULL;
  1472. if (key->shake128_md != NULL
  1473. && key->shake256_md != NULL
  1474. && key->sha3_256_md != NULL
  1475. && key->sha3_512_md != NULL)
  1476. return key;
  1477. ossl_ml_kem_key_free(key);
  1478. ERR_raise_data(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR,
  1479. "missing SHA3 digest algorithms while creating %s key",
  1480. vinfo->algorithm_name);
  1481. return NULL;
  1482. }
  1483. ML_KEM_KEY *ossl_ml_kem_key_dup(const ML_KEM_KEY *key, int selection)
  1484. {
  1485. int ok = 0;
  1486. ML_KEM_KEY *ret;
  1487. /*
  1488. * Partially decoded keys, not yet imported or loaded, should never be
  1489. * duplicated.
  1490. */
  1491. if (ossl_ml_kem_decoded_key(key))
  1492. return NULL;
  1493. if (key == NULL
  1494. || (ret = OPENSSL_memdup(key, sizeof(*key))) == NULL)
  1495. return NULL;
  1496. ret->d = ret->z = ret->rho = ret->pkhash = NULL;
  1497. ret->s = ret->m = ret->t = NULL;
  1498. /* Clear selection bits we can't fulfill */
  1499. if (!ossl_ml_kem_have_pubkey(key))
  1500. selection = 0;
  1501. else if (!ossl_ml_kem_have_prvkey(key))
  1502. selection &= ~OSSL_KEYMGMT_SELECT_PRIVATE_KEY;
  1503. switch (selection & OSSL_KEYMGMT_SELECT_KEYPAIR) {
  1504. case 0:
  1505. ok = 1;
  1506. break;
  1507. case OSSL_KEYMGMT_SELECT_PUBLIC_KEY:
  1508. ok = add_storage(OPENSSL_memdup(key->t, key->vinfo->puballoc), 0, ret);
  1509. ret->rho = ret->seedbuf;
  1510. ret->pkhash = ret->rho + ML_KEM_RANDOM_BYTES;
  1511. break;
  1512. case OSSL_KEYMGMT_SELECT_PRIVATE_KEY:
  1513. ok = add_storage(OPENSSL_memdup(key->t, key->vinfo->prvalloc), 1, ret);
  1514. /* Duplicated keys retain |d|, if available */
  1515. if (key->d != NULL)
  1516. ret->d = ret->z + ML_KEM_RANDOM_BYTES;
  1517. break;
  1518. }
  1519. if (!ok) {
  1520. OPENSSL_free(ret);
  1521. return NULL;
  1522. }
  1523. EVP_MD_up_ref(ret->shake128_md);
  1524. EVP_MD_up_ref(ret->shake256_md);
  1525. EVP_MD_up_ref(ret->sha3_256_md);
  1526. EVP_MD_up_ref(ret->sha3_512_md);
  1527. return ret;
  1528. }
  1529. void ossl_ml_kem_key_free(ML_KEM_KEY *key)
  1530. {
  1531. if (key == NULL)
  1532. return;
  1533. EVP_MD_free(key->shake128_md);
  1534. EVP_MD_free(key->shake256_md);
  1535. EVP_MD_free(key->sha3_256_md);
  1536. EVP_MD_free(key->sha3_512_md);
  1537. if (ossl_ml_kem_decoded_key(key)) {
  1538. OPENSSL_cleanse(key->seedbuf, sizeof(key->seedbuf));
  1539. if (ossl_ml_kem_have_dkenc(key)) {
  1540. OPENSSL_cleanse(key->encoded_dk, key->vinfo->prvkey_bytes);
  1541. OPENSSL_free(key->encoded_dk);
  1542. }
  1543. }
  1544. ossl_ml_kem_key_reset(key);
  1545. OPENSSL_free(key);
  1546. }
  1547. /* Serialise the public component of an ML-KEM key */
  1548. int ossl_ml_kem_encode_public_key(uint8_t *out, size_t len,
  1549. const ML_KEM_KEY *key)
  1550. {
  1551. if (!ossl_ml_kem_have_pubkey(key)
  1552. || len != key->vinfo->pubkey_bytes)
  1553. return 0;
  1554. encode_pubkey(out, key);
  1555. return 1;
  1556. }
  1557. /* Serialise an ML-KEM private key */
  1558. int ossl_ml_kem_encode_private_key(uint8_t *out, size_t len,
  1559. const ML_KEM_KEY *key)
  1560. {
  1561. if (!ossl_ml_kem_have_prvkey(key)
  1562. || len != key->vinfo->prvkey_bytes)
  1563. return 0;
  1564. encode_prvkey(out, key);
  1565. return 1;
  1566. }
  1567. int ossl_ml_kem_encode_seed(uint8_t *out, size_t len,
  1568. const ML_KEM_KEY *key)
  1569. {
  1570. if (key == NULL || key->d == NULL || len != ML_KEM_SEED_BYTES)
  1571. return 0;
  1572. /*
  1573. * Both in the seed buffer, and in the allocated storage, the |d| component
  1574. * of the seed is stored last, so we must copy each separately.
  1575. */
  1576. memcpy(out, key->d, ML_KEM_RANDOM_BYTES);
  1577. out += ML_KEM_RANDOM_BYTES;
  1578. memcpy(out, key->z, ML_KEM_RANDOM_BYTES);
  1579. return 1;
  1580. }
  1581. /*
  1582. * Stash the seed without (yet) performing a keygen, used during decoding, to
  1583. * avoid an extra keygen if we're only going to export the key again to load
  1584. * into another provider.
  1585. */
  1586. ML_KEM_KEY *ossl_ml_kem_set_seed(const uint8_t *seed, size_t seedlen, ML_KEM_KEY *key)
  1587. {
  1588. if (key == NULL
  1589. || ossl_ml_kem_have_pubkey(key)
  1590. || ossl_ml_kem_have_seed(key)
  1591. || seedlen != ML_KEM_SEED_BYTES)
  1592. return NULL;
  1593. /*
  1594. * With no public or private key material on hand, we can use the seed
  1595. * buffer for |z| and |d|, in that order.
  1596. */
  1597. key->z = key->seedbuf;
  1598. key->d = key->z + ML_KEM_RANDOM_BYTES;
  1599. memcpy(key->d, seed, ML_KEM_RANDOM_BYTES);
  1600. seed += ML_KEM_RANDOM_BYTES;
  1601. memcpy(key->z, seed, ML_KEM_RANDOM_BYTES);
  1602. return key;
  1603. }
  1604. /* Parse input as a public key */
  1605. int ossl_ml_kem_parse_public_key(const uint8_t *in, size_t len, ML_KEM_KEY *key)
  1606. {
  1607. EVP_MD_CTX *mdctx = NULL;
  1608. const ML_KEM_VINFO *vinfo;
  1609. int ret = 0;
  1610. /* Keys with key material are immutable */
  1611. if (key == NULL
  1612. || ossl_ml_kem_have_pubkey(key)
  1613. || ossl_ml_kem_have_dkenc(key))
  1614. return 0;
  1615. vinfo = key->vinfo;
  1616. if (len != vinfo->pubkey_bytes
  1617. || (mdctx = EVP_MD_CTX_new()) == NULL)
  1618. return 0;
  1619. if (add_storage(OPENSSL_malloc(vinfo->puballoc), 0, key))
  1620. ret = parse_pubkey(in, mdctx, key);
  1621. if (!ret)
  1622. ossl_ml_kem_key_reset(key);
  1623. EVP_MD_CTX_free(mdctx);
  1624. return ret;
  1625. }
  1626. /* Parse input as a new private key */
  1627. int ossl_ml_kem_parse_private_key(const uint8_t *in, size_t len,
  1628. ML_KEM_KEY *key)
  1629. {
  1630. EVP_MD_CTX *mdctx = NULL;
  1631. const ML_KEM_VINFO *vinfo;
  1632. int ret = 0;
  1633. /* Keys with key material are immutable */
  1634. if (key == NULL
  1635. || ossl_ml_kem_have_pubkey(key)
  1636. || ossl_ml_kem_have_dkenc(key))
  1637. return 0;
  1638. vinfo = key->vinfo;
  1639. if (len != vinfo->prvkey_bytes
  1640. || (mdctx = EVP_MD_CTX_new()) == NULL)
  1641. return 0;
  1642. if (add_storage(OPENSSL_malloc(vinfo->prvalloc), 1, key))
  1643. ret = parse_prvkey(in, mdctx, key);
  1644. if (!ret)
  1645. ossl_ml_kem_key_reset(key);
  1646. EVP_MD_CTX_free(mdctx);
  1647. return ret;
  1648. }
  1649. /*
  1650. * Generate a new keypair, either from the saved seed (when non-null), or from
  1651. * the RNG.
  1652. */
  1653. int ossl_ml_kem_genkey(uint8_t *pubenc, size_t publen, ML_KEM_KEY *key)
  1654. {
  1655. uint8_t seed[ML_KEM_SEED_BYTES];
  1656. EVP_MD_CTX *mdctx = NULL;
  1657. const ML_KEM_VINFO *vinfo;
  1658. int ret = 0;
  1659. if (key == NULL
  1660. || ossl_ml_kem_have_pubkey(key)
  1661. || ossl_ml_kem_have_dkenc(key))
  1662. return 0;
  1663. vinfo = key->vinfo;
  1664. if (pubenc != NULL && publen != vinfo->pubkey_bytes)
  1665. return 0;
  1666. if (ossl_ml_kem_have_seed(key)) {
  1667. if (!ossl_ml_kem_encode_seed(seed, sizeof(seed), key))
  1668. return 0;
  1669. key->d = key->z = NULL;
  1670. } else if (RAND_priv_bytes_ex(key->libctx, seed, sizeof(seed),
  1671. key->vinfo->secbits) <= 0) {
  1672. return 0;
  1673. }
  1674. if ((mdctx = EVP_MD_CTX_new()) == NULL)
  1675. return 0;
  1676. /*
  1677. * Data derived from (d, z) defaults secret, and to avoid side-channel
  1678. * leaks should not influence control flow.
  1679. */
  1680. CONSTTIME_SECRET(seed, ML_KEM_SEED_BYTES);
  1681. if (add_storage(OPENSSL_malloc(vinfo->prvalloc), 1, key))
  1682. ret = genkey(seed, mdctx, pubenc, key);
  1683. OPENSSL_cleanse(seed, sizeof(seed));
  1684. /* Declassify secret inputs and derived outputs before returning control */
  1685. CONSTTIME_DECLASSIFY(seed, ML_KEM_SEED_BYTES);
  1686. EVP_MD_CTX_free(mdctx);
  1687. if (!ret) {
  1688. ossl_ml_kem_key_reset(key);
  1689. return 0;
  1690. }
  1691. /* The public components are already declassified */
  1692. CONSTTIME_DECLASSIFY(key->s, vinfo->rank * sizeof(scalar));
  1693. CONSTTIME_DECLASSIFY(key->z, 2 * ML_KEM_RANDOM_BYTES);
  1694. return 1;
  1695. }
  1696. /*
  1697. * FIPS 203, Section 6.2, Algorithm 17: ML-KEM.Encaps_internal
  1698. * This is the deterministic version with randomness supplied externally.
  1699. */
  1700. int ossl_ml_kem_encap_seed(uint8_t *ctext, size_t clen,
  1701. uint8_t *shared_secret, size_t slen,
  1702. const uint8_t *entropy, size_t elen,
  1703. const ML_KEM_KEY *key)
  1704. {
  1705. const ML_KEM_VINFO *vinfo;
  1706. EVP_MD_CTX *mdctx;
  1707. int ret = 0;
  1708. if (key == NULL || !ossl_ml_kem_have_pubkey(key))
  1709. return 0;
  1710. vinfo = key->vinfo;
  1711. if (ctext == NULL || clen != vinfo->ctext_bytes
  1712. || shared_secret == NULL || slen != ML_KEM_SHARED_SECRET_BYTES
  1713. || entropy == NULL || elen != ML_KEM_RANDOM_BYTES
  1714. || (mdctx = EVP_MD_CTX_new()) == NULL)
  1715. return 0;
  1716. /*
  1717. * Data derived from the encap entropy defaults secret, and to avoid
  1718. * side-channel leaks should not influence control flow.
  1719. */
  1720. CONSTTIME_SECRET(entropy, elen);
  1721. /*-
  1722. * This avoids the need to handle allocation failures for two (max 2KB
  1723. * each) vectors, that are never retained on return from this function.
  1724. * We stack-allocate these.
  1725. */
  1726. # define case_encap_seed(bits) \
  1727. case EVP_PKEY_ML_KEM_##bits: \
  1728. { \
  1729. scalar tmp[2 * ML_KEM_##bits##_RANK]; \
  1730. \
  1731. ret = encap(ctext, shared_secret, entropy, tmp, mdctx, key); \
  1732. OPENSSL_cleanse((void *)tmp, sizeof(tmp)); \
  1733. break; \
  1734. }
  1735. switch (vinfo->evp_type) {
  1736. case_encap_seed(512);
  1737. case_encap_seed(768);
  1738. case_encap_seed(1024);
  1739. }
  1740. # undef case_encap_seed
  1741. /* Declassify secret inputs and derived outputs before returning control */
  1742. CONSTTIME_DECLASSIFY(entropy, elen);
  1743. CONSTTIME_DECLASSIFY(ctext, clen);
  1744. CONSTTIME_DECLASSIFY(shared_secret, slen);
  1745. EVP_MD_CTX_free(mdctx);
  1746. return ret;
  1747. }
  1748. int ossl_ml_kem_encap_rand(uint8_t *ctext, size_t clen,
  1749. uint8_t *shared_secret, size_t slen,
  1750. const ML_KEM_KEY *key)
  1751. {
  1752. uint8_t r[ML_KEM_RANDOM_BYTES];
  1753. if (key == NULL)
  1754. return 0;
  1755. if (RAND_bytes_ex(key->libctx, r, ML_KEM_RANDOM_BYTES,
  1756. key->vinfo->secbits) < 1)
  1757. return 0;
  1758. return ossl_ml_kem_encap_seed(ctext, clen, shared_secret, slen,
  1759. r, sizeof(r), key);
  1760. }
  1761. int ossl_ml_kem_decap(uint8_t *shared_secret, size_t slen,
  1762. const uint8_t *ctext, size_t clen,
  1763. const ML_KEM_KEY *key)
  1764. {
  1765. const ML_KEM_VINFO *vinfo;
  1766. EVP_MD_CTX *mdctx;
  1767. int ret = 0;
  1768. #if defined(OPENSSL_CONSTANT_TIME_VALIDATION)
  1769. int classify_bytes;
  1770. #endif
  1771. /* Need a private key here */
  1772. if (!ossl_ml_kem_have_prvkey(key))
  1773. return 0;
  1774. vinfo = key->vinfo;
  1775. if (shared_secret == NULL || slen != ML_KEM_SHARED_SECRET_BYTES
  1776. || ctext == NULL || clen != vinfo->ctext_bytes
  1777. || (mdctx = EVP_MD_CTX_new()) == NULL) {
  1778. (void)RAND_bytes_ex(key->libctx, shared_secret,
  1779. ML_KEM_SHARED_SECRET_BYTES, vinfo->secbits);
  1780. return 0;
  1781. }
  1782. #if defined(OPENSSL_CONSTANT_TIME_VALIDATION)
  1783. /*
  1784. * Data derived from |s| and |z| defaults secret, and to avoid side-channel
  1785. * leaks should not influence control flow.
  1786. */
  1787. classify_bytes = 2 * sizeof(scalar) + ML_KEM_RANDOM_BYTES;
  1788. CONSTTIME_SECRET(key->s, classify_bytes);
  1789. #endif
  1790. /*-
  1791. * This avoids the need to handle allocation failures for two (max 2KB
  1792. * each) vectors and an encoded ciphertext (max 1568 bytes), that are never
  1793. * retained on return from this function.
  1794. * We stack-allocate these.
  1795. */
  1796. # define case_decap(bits) \
  1797. case EVP_PKEY_ML_KEM_##bits: \
  1798. { \
  1799. uint8_t cbuf[CTEXT_BYTES(bits)]; \
  1800. scalar tmp[2 * ML_KEM_##bits##_RANK]; \
  1801. \
  1802. ret = decap(shared_secret, ctext, cbuf, tmp, mdctx, key); \
  1803. OPENSSL_cleanse((void *)tmp, sizeof(tmp)); \
  1804. break; \
  1805. }
  1806. switch (vinfo->evp_type) {
  1807. case_decap(512);
  1808. case_decap(768);
  1809. case_decap(1024);
  1810. }
  1811. /* Declassify secret inputs and derived outputs before returning control */
  1812. CONSTTIME_DECLASSIFY(key->s, classify_bytes);
  1813. CONSTTIME_DECLASSIFY(shared_secret, slen);
  1814. EVP_MD_CTX_free(mdctx);
  1815. return ret;
  1816. # undef case_decap
  1817. }
  1818. int ossl_ml_kem_pubkey_cmp(const ML_KEM_KEY *key1, const ML_KEM_KEY *key2)
  1819. {
  1820. /*
  1821. * This handles any unexpected differences in the ML-KEM variant rank,
  1822. * giving different key component structures, barring SHA3-256 hash
  1823. * collisions, the keys are the same size.
  1824. */
  1825. if (ossl_ml_kem_have_pubkey(key1) && ossl_ml_kem_have_pubkey(key2))
  1826. return memcmp(key1->pkhash, key2->pkhash, ML_KEM_PKHASH_BYTES) == 0;
  1827. /*
  1828. * No match if just one of the public keys is not available, otherwise both
  1829. * are unavailable, and for now such keys are considered equal.
  1830. */
  1831. return (!(ossl_ml_kem_have_pubkey(key1) ^ ossl_ml_kem_have_pubkey(key2)));
  1832. }