Coverage Report

Created: 2026-12-01 07:02

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/wolfssl/wolfcrypt/src/wc_mlkem.c
Line
Count
Source
1
/* wc_mlkem.c
2
 *
3
 * Copyright (C) 2006-2026 wolfSSL Inc.
4
 *
5
 * This file is part of wolfSSL.
6
 *
7
 * wolfSSL is free software; you can redistribute it and/or modify
8
 * it under the terms of the GNU General Public License as published by
9
 * the Free Software Foundation; either version 3 of the License, or
10
 * (at your option) any later version.
11
 *
12
 * wolfSSL is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU General Public License
18
 * along with this program; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
20
 */
21
22
/* Implementation based on FIPS 203:
23
 *   https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.203.pdf
24
 *
25
 * Original implementation based on NIST 3rd Round submission package.
26
 * See link at:
27
 *   https://csrc.nist.gov/Projects/post-quantum-cryptography/
28
 *   post-quantum-cryptography-standardization/round-3-submissions
29
 */
30
31
/* Possible ML-KEM options:
32
 *
33
 * WOLFSSL_MLKEM_MAKEKEY_SMALL_MEM                                 Default: OFF
34
 *   Uses less dynamic memory to perform key generation.
35
 *   Matrix A is generated a polynomial at a time.
36
 *   Has a small performance trade-off.
37
 *   Only usable with C implementation.
38
 *
39
 * WOLFSSL_MLKEM_ENCAPSULATE_SMALL_MEM                             Default: OFF
40
 *   Uses less dynamic memory to perform encapsulation.
41
 *   Affects decapsulation too as encapsulation called.
42
 *   Matrix A and u are handled a polynomial at a time.
43
 *   Has a small performance trade-off.
44
 *   Only usable with C implementation.
45
 *
46
 * WOLFSSL_MLKEM_NO_MAKE_KEY                                       Default: OFF
47
 *   Disable the make key or key generation API.
48
 *   Reduces the code size.
49
 *   Turn on when only doing encapsulation.
50
 *
51
 * WOLFSSL_MLKEM_NO_ENCAPSULATE                                    Default: OFF
52
 *   Disable the encapsulation API.
53
 *   Reduces the code size.
54
 *   Turn on when doing make key/decapsulation.
55
 *
56
 * WOLFSSL_MLKEM_NO_DECAPSULATE                                    Default: OFF
57
 *   Disable the decapsulation API.
58
 *   Reduces the code size.
59
 *   Turn on when only doing encapsulation.
60
 *
61
 * WOLFSSL_MLKEM_CACHE_A                                           Default: OFF
62
 *   Stores the matrix A during key generation for use in encapsulation when
63
 *   performing decapsulation.
64
 *   MlKemKey is 8KB larger but decapsulation is significantly faster.
65
 *   Turn on when performing make key and decapsulation with same object.
66
 *   Also usable with the small memory options.
67
 *   Encapsulation also keeps A for a decoded key that has room for it.
68
 *
69
 * WOLFSSL_MLKEM_DYNAMIC_KEYS                                      Default: OFF
70
 *   Dynamically allocates private and public key buffers instead of using
71
 *   static arrays in the MlKemKey struct. Right-sizes buffers to the actual
72
 *   ML-KEM level and only allocates the needed key parts (e.g., no private
73
 *   key buffer for encapsulate-only use).
74
 *   Cannot be used with WOLFSSL_NO_MALLOC.
75
 */
76
77
#define WC_FIPS_LL_CRYPTO
78
#define _WC_BUILDING_WC_MLKEM_C
79
80
#include <wolfssl/wolfcrypt/libwolfssl_sources.h>
81
82
#ifdef WOLFSSL_HAVE_MLKEM
83
84
#if FIPS_VERSION3_GE(7,0,0)
85
    #if defined(USE_WINDOWS_API) && defined(_MSC_VER)
86
        #pragma code_seg(".fipsA$na")
87
        #pragma const_seg(".fipsB$na")
88
    #endif
89
#endif
90
91
#ifdef WC_MLKEM_NO_ASM
92
    #undef USE_INTEL_SPEEDUP
93
    #undef WOLFSSL_ARMASM
94
    #undef WOLFSSL_RISCV_ASM
95
#endif
96
97
#include <wolfssl/wolfcrypt/wc_mlkem.h>
98
99
#include <wolfssl/wolfcrypt/hash.h>
100
#include <wolfssl/wolfcrypt/memory.h>
101
102
/* aarch64 claim around the NEON helpers in wc_mlkem_poly.c.  stmt runs only
103
 * when ret is 0; other builds run stmt as is. */
104
#if defined(__aarch64__) && defined(WOLFSSL_ARMASM)
105
    #define MLKEM_ARM64_SVR(stmt)                   \
106
        do {                                        \
107
            ret = SAVE_VECTOR_REGISTERS2();         \
108
            if (ret == 0) {                         \
109
                stmt;                               \
110
                RESTORE_VECTOR_REGISTERS();         \
111
            }                                       \
112
        } while (0)
113
#else
114
0
    #define MLKEM_ARM64_SVR(stmt) do { stmt; } while (0)
115
#endif
116
#ifdef WOLF_CRYPTO_CB
117
    #include <wolfssl/wolfcrypt/cryptocb.h>
118
#endif
119
#ifndef WOLFSSL_MLKEM_NO_ASN1
120
    #include <wolfssl/wolfcrypt/asn.h>
121
#endif
122
123
#ifdef NO_INLINE
124
    #include <wolfssl/wolfcrypt/misc.h>
125
#else
126
    #define WOLFSSL_MISC_INCLUDED
127
    #include <wolfcrypt/src/misc.c>
128
#endif
129
130
#if defined(USE_INTEL_SPEEDUP) || \
131
    (defined(__aarch64__) && defined(WOLFSSL_ARMASM))
132
    #if defined(WOLFSSL_MLKEM_MAKEKEY_SMALL_MEM) || \
133
        defined(WOLFSSL_MLKEM_ENCAPSULATE_SMALL_MEM)
134
        #error "Can't use small memory with assembly optimized code"
135
    #endif
136
#endif
137
138
#if defined(WOLFSSL_MLKEM_NO_MAKE_KEY) && \
139
    defined(WOLFSSL_MLKEM_NO_ENCAPSULATE) && \
140
    defined(WOLFSSL_MLKEM_NO_DECAPSULATE)
141
    #error "No ML-KEM operations to be built."
142
#endif
143
#if defined(WOLFSSL_MLKEM_DYNAMIC_KEYS) && defined(WOLFSSL_NO_MALLOC)
144
    #error "Cannot use dynamic key buffers without malloc"
145
#endif
146
147
/* Non-blocking (chunked) keygen/encapsulate/decapsulate is built only on the
148
 * small-memory paths, which already process a row/polynomial at a time. */
149
#ifdef WC_MLKEM_NONBLOCK
150
    #ifdef WOLF_CRYPTO_CB_ONLY_MLKEM
151
        #error "WC_MLKEM_NONBLOCK needs the software implementation"
152
    #endif
153
    #if !defined(WOLFSSL_MLKEM_NO_MAKE_KEY) && \
154
        !defined(WOLFSSL_MLKEM_MAKEKEY_SMALL_MEM)
155
        #error "WC_MLKEM_NONBLOCK requires WOLFSSL_MLKEM_MAKEKEY_SMALL_MEM"
156
    #endif
157
    /* Decapsulate re-encrypts, so it needs the small-mem encapsulate path
158
     * too. */
159
    #if (!defined(WOLFSSL_MLKEM_NO_ENCAPSULATE) || \
160
         !defined(WOLFSSL_MLKEM_NO_DECAPSULATE)) && \
161
        !defined(WOLFSSL_MLKEM_ENCAPSULATE_SMALL_MEM)
162
        #error "WC_MLKEM_NONBLOCK requires WOLFSSL_MLKEM_ENCAPSULATE_SMALL_MEM"
163
    #endif
164
    #if !defined(WOLFSSL_MLKEM_NO_MAKE_KEY) && \
165
        (FIPS_VERSION3_GE(7,0,0) || defined(WOLFSSL_VALIDATE_MLKEM_KEYGEN))
166
        #error "WC_MLKEM_NONBLOCK keygen unsupported with the keygen PCT"
167
    #endif
168
    #ifdef WOLFSSL_NO_MALLOC
169
        #error "WC_MLKEM_NONBLOCK keeps working vectors on the heap"
170
    #endif
171
/* Operation that owns a non-blocking context. */
172
#define MLKEM_NB_OP_MAKE    1
173
#define MLKEM_NB_OP_ENCAP   2
174
#define MLKEM_NB_OP_DECAP   3
175
176
static void mlkemkey_nb_release(MlKemKey* key);
177
static int mlkemkey_nb_begin(MlKemKey* key, byte op, const byte* bind,
178
    word32 sz, const void* arg);
179
#endif /* WC_MLKEM_NONBLOCK */
180
181
#if defined(WOLFSSL_KYBER1024) || defined(WOLFSSL_WC_ML_KEM_1024)
182
    #define MLKEM_MAX_COMP_POLY_SZ  MLKEM_POLY_COMPRESSED_SZ(11)
183
#else
184
    #define MLKEM_MAX_COMP_POLY_SZ  MLKEM_POLY_COMPRESSED_SZ(10)
185
#endif
186
187
#if FIPS_VERSION3_GE(7,0,0)
188
    const unsigned int wolfCrypt_FIPS_mlkem_ro_sanity[2] =
189
                                                     { 0x1a2b3c4d, 0x00000019 };
190
    int wolfCrypt_FIPS_MLKEM_sanity(void)
191
    {
192
        return 0;
193
    }
194
#endif
195
196
#ifdef DEBUG_MLKEM
197
void print_polys(const char* name, const sword16* a, int d1, int d2);
198
void print_polys(const char* name, const sword16* a, int d1, int d2)
199
{
200
    int i;
201
    int j;
202
    int k;
203
204
    fprintf(stderr, "%s: %d %d\n", name, d1, d2);
205
    for (i = 0; i < d1; i++) {
206
        for (j = 0; j < d2; j++) {
207
            for (k = 0; k < 256; k++) {
208
                fprintf(stderr, "%9d,", a[(i*d2*256) + (j*256) + k]);
209
                if ((k % 8) == 7) fprintf(stderr, "\n");
210
            }
211
            fprintf(stderr, "\n");
212
        }
213
    }
214
}
215
#endif
216
217
#ifdef DEBUG_MLKEM
218
void print_data(const char* name, const byte* d, int len);
219
void print_data(const char* name, const byte* d, int len)
220
{
221
    int i;
222
223
    fprintf(stderr, "%s\n", name);
224
    for (i = 0; i < len; i++) {
225
        fprintf(stderr, "0x%02x,", d[i]);
226
        if ((i % 16) == 15) fprintf(stderr, "\n");
227
    }
228
    fprintf(stderr, "\n");
229
}
230
#endif
231
232
/******************************************************************************/
233
234
/* Use SHA3-256 to generate 32-bytes of hash. */
235
0
#define MLKEM_HASH_H            mlkem_hash256
236
/* Use SHA3-512 to generate 64-bytes of hash. */
237
0
#define MLKEM_HASH_G            mlkem_hash512
238
/* Use SHAKE-256 as a key derivation function (KDF). */
239
#if defined(USE_INTEL_SPEEDUP) || \
240
        (defined(WOLFSSL_ARMASM) && defined(__aarch64__))
241
    #define MLKEM_KDF               mlkem_kdf
242
#else
243
    #define MLKEM_KDF               wc_Shake256Hash
244
#endif
245
246
/* A key named by id, label or device context is held by a device. */
247
#if defined(WOLF_CRYPTO_CB) && defined(WOLF_PRIVATE_KEY_ID)
248
    #define MLKEM_KEY_ON_DEVICE(key) (((key)->devCtx != NULL) || \
249
        ((key)->idLen > 0) || ((key)->labelLen > 0))
250
#elif defined(WOLF_CRYPTO_CB)
251
    #define MLKEM_KEY_ON_DEVICE(key) ((key)->devCtx != NULL)
252
#else
253
0
    #define MLKEM_KEY_ON_DEVICE(key) 0
254
#endif
255
256
/******************************************************************************/
257
258
/* Helper function with volatile variable, to force compiler not to optimize
259
 * code in mlkem_from_msg().
260
 */
261
sword16 wc_mlkem_opt_blocker(void);
262
0
sword16 wc_mlkem_opt_blocker(void) {
263
0
    static volatile sword16 static_mlkem_opt_blocker = 0;
264
0
    return static_mlkem_opt_blocker;
265
0
}
266
267
/******************************************************************************/
268
269
#ifndef WOLFSSL_MLKEM_NO_MAKE_KEY
270
/* Get the k value (number of polynomials in a vector) from the key type.
271
 *
272
 * @param  [in]  key  ML-KEM key object.
273
 * @return  k value for the key type, or 0 if not recognized.
274
 */
275
#ifndef WOLF_CRYPTO_CB_ONLY_MLKEM
276
static int mlkemkey_get_k(const MlKemKey* key)
277
0
{
278
0
    switch (key->type) {
279
0
#ifndef WOLFSSL_NO_ML_KEM
280
0
    #ifdef WOLFSSL_WC_ML_KEM_512
281
0
        case WC_ML_KEM_512:
282
0
            return WC_ML_KEM_512_K;
283
0
    #endif
284
0
    #ifdef WOLFSSL_WC_ML_KEM_768
285
0
        case WC_ML_KEM_768:
286
0
            return WC_ML_KEM_768_K;
287
0
    #endif
288
0
    #ifdef WOLFSSL_WC_ML_KEM_1024
289
0
        case WC_ML_KEM_1024:
290
0
            return WC_ML_KEM_1024_K;
291
0
    #endif
292
0
#endif
293
#ifdef WOLFSSL_MLKEM_KYBER
294
    #ifdef WOLFSSL_KYBER512
295
        case KYBER512:
296
            return KYBER512_K;
297
    #endif
298
    #ifdef WOLFSSL_KYBER768
299
        case KYBER768:
300
            return KYBER768_K;
301
    #endif
302
    #ifdef WOLFSSL_KYBER1024
303
        case KYBER1024:
304
            return KYBER1024_K;
305
    #endif
306
#endif
307
0
        default:
308
0
            return 0;
309
0
    }
310
0
}
311
#endif /* !WOLF_CRYPTO_CB_ONLY_MLKEM */
312
#endif
313
314
#ifdef WOLFSSL_MLKEM_DYNAMIC_KEYS
315
/* Allocate (or reallocate) the private key buffer, right-sized for k.
316
 *
317
 * @param  [in, out]  key  ML-KEM key object.
318
 * @param  [in]       k    Number of polynomials in a vector.
319
 * @return  0 on success.
320
 * @return  MEMORY_E when dynamic memory allocation fails.
321
 */
322
static int mlkemkey_alloc_priv(MlKemKey* key, unsigned int k)
323
{
324
    word32 sz = (word32)(k * MLKEM_N * sizeof(sword16));
325
    if (key->priv != NULL) {
326
        ForceZero(key->priv, key->privAllocSz);
327
        XFREE(key->priv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
328
        key->priv = NULL;
329
        key->privAllocSz = 0;
330
    }
331
    key->priv = (sword16*)XMALLOC(sz, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
332
    if (key->priv == NULL) {
333
        return MEMORY_E;
334
    }
335
    key->privAllocSz = sz;
336
    return 0;
337
}
338
339
/* Allocate (or reallocate) the public key buffer, right-sized for k.
340
 *
341
 * @param  [in, out]  key  ML-KEM key object.
342
 * @param  [in]       k    Number of polynomials in a vector.
343
 * @return  0 on success.
344
 * @return  MEMORY_E when dynamic memory allocation fails.
345
 */
346
static int mlkemkey_alloc_pub(MlKemKey* key, unsigned int k)
347
{
348
    if (key->pub != NULL) {
349
        XFREE(key->pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
350
        key->pub = NULL;
351
    }
352
    key->pub = (sword16*)XMALLOC(k * MLKEM_N * sizeof(sword16), key->heap,
353
        DYNAMIC_TYPE_TMP_BUFFER);
354
    if (key->pub == NULL) {
355
        return MEMORY_E;
356
    }
357
    return 0;
358
}
359
360
#if defined(WOLFSSL_MLKEM_CACHE_A) && !defined(WOLFSSL_MLKEM_NO_MAKE_KEY)
361
/* Allocate (or reallocate) the A matrix buffer, right-sized for k.
362
 *
363
 * @param  [in, out]  key  ML-KEM key object.
364
 * @param  [in]       k    Number of polynomials in a vector.
365
 * @return  0 on success.
366
 * @return  MEMORY_E when dynamic memory allocation fails.
367
 */
368
static int mlkemkey_alloc_a(MlKemKey* key, unsigned int k)
369
{
370
    int ret = 0;
371
372
    if (key->a != NULL) {
373
        XFREE(key->a, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
374
        key->a = NULL;
375
    }
376
    key->a = (sword16*)XMALLOC(k * k * MLKEM_N * sizeof(sword16), key->heap,
377
        DYNAMIC_TYPE_TMP_BUFFER);
378
    if (key->a == NULL) {
379
        ret = MEMORY_E;
380
    }
381
382
    return ret;
383
}
384
#endif /* WOLFSSL_MLKEM_CACHE_A && !WOLFSSL_MLKEM_NO_MAKE_KEY */
385
#endif /* WOLFSSL_MLKEM_DYNAMIC_KEYS */
386
387
/******************************************************************************/
388
389
#ifndef WC_NO_CONSTRUCTORS
390
/**
391
 * Create a new ML-KEM key object.
392
 *
393
 * Allocates and initializes a ML-KEM key object.
394
 *
395
 * @param  [in]  type   Type of key:
396
 *                        WC_ML_KEM_512, WC_ML_KEM_768, WC_ML_KEM_1024,
397
 *                        KYBER512, KYBER768, KYBER1024.
398
 * @param  [in]  heap   Dynamic memory hint.
399
 * @param  [in]  devId  Device Id.
400
 * @return  Pointer to new MlKemKey object on success.
401
 * @return  NULL on failure.
402
 */
403
MlKemKey* wc_MlKemKey_New(int type, void* heap, int devId)
404
0
{
405
0
    int ret;
406
0
    MlKemKey* key;
407
408
0
    key = (MlKemKey*)XMALLOC(sizeof(MlKemKey), heap, DYNAMIC_TYPE_TMP_BUFFER);
409
0
    if (key != NULL) {
410
0
        ret = wc_MlKemKey_Init(key, type, heap, devId);
411
0
        if (ret != 0) {
412
0
            XFREE(key, heap, DYNAMIC_TYPE_TMP_BUFFER);
413
0
            key = NULL;
414
0
        }
415
0
    }
416
417
0
    return key;
418
0
}
419
420
/**
421
 * Delete and free a ML-KEM key object.
422
 *
423
 * Frees resources associated with a ML-KEM key object and sets pointer to NULL.
424
 *
425
 * @param  [in]       key    ML-KEM key object to delete.
426
 * @param  [in, out]  key_p  Pointer to key pointer to set to NULL.
427
 * @return  0 on success.
428
 * @return  BAD_FUNC_ARG when key is NULL.
429
 */
430
int wc_MlKemKey_Delete(MlKemKey* key, MlKemKey** key_p)
431
0
{
432
0
    int ret = 0;
433
434
0
    if (key == NULL) {
435
0
        ret = BAD_FUNC_ARG;
436
0
    }
437
0
    else {
438
0
        void* heap = key->heap;
439
440
0
        ret = wc_MlKemKey_Free(key);
441
0
        XFREE(key, heap, DYNAMIC_TYPE_TMP_BUFFER);
442
0
        if (key_p != NULL) {
443
0
            *key_p = NULL;
444
0
        }
445
0
    }
446
447
0
    return ret;
448
0
}
449
#endif /* !WC_NO_CONSTRUCTORS */
450
451
/**
452
 * Initialize the ML-KEM key.
453
 *
454
 * @param  [out]  key    ML-KEM key object to initialize.
455
 * @param  [in]   type   Type of key:
456
 *                         WC_ML_KEM_512, WC_ML_KEM_768, WC_ML_KEM_1024,
457
 *                         KYBER512, KYBER768, KYBER1024.
458
 * @param  [in]   heap   Dynamic memory hint.
459
 * @param  [in]   devId  Device Id.
460
 * @return  0 on success.
461
 * @return  BAD_FUNC_ARG when key is NULL or type is unrecognized.
462
 * @return  NOT_COMPILED_IN when key type is not supported.
463
 */
464
int wc_MlKemKey_Init(MlKemKey* key, int type, void* heap, int devId)
465
0
{
466
0
    int ret = 0;
467
468
    /* Validate key. */
469
0
    if (key == NULL) {
470
0
        ret = BAD_FUNC_ARG;
471
0
    }
472
0
    if (ret == 0) {
473
        /* Validate type. */
474
0
        switch (type) {
475
0
    #ifndef WOLFSSL_NO_ML_KEM
476
0
        case WC_ML_KEM_512:
477
        #ifndef WOLFSSL_WC_ML_KEM_512
478
            /* Code not compiled in for ML-KEM-512. */
479
            ret = NOT_COMPILED_IN;
480
        #endif
481
0
            break;
482
0
        case WC_ML_KEM_768:
483
        #ifndef WOLFSSL_WC_ML_KEM_768
484
            /* Code not compiled in for ML-KEM-768. */
485
            ret = NOT_COMPILED_IN;
486
        #endif
487
0
            break;
488
0
        case WC_ML_KEM_1024:
489
        #ifndef WOLFSSL_WC_ML_KEM_1024
490
            /* Code not compiled in for ML-KEM-1024. */
491
            ret = NOT_COMPILED_IN;
492
        #endif
493
0
            break;
494
0
    #endif
495
    #ifdef WOLFSSL_MLKEM_KYBER
496
        case KYBER512:
497
        #ifndef WOLFSSL_KYBER512
498
            /* Code not compiled in for Kyber-512. */
499
            ret = NOT_COMPILED_IN;
500
        #endif
501
            break;
502
        case KYBER768:
503
        #ifndef WOLFSSL_KYBER768
504
            /* Code not compiled in for Kyber-768. */
505
            ret = NOT_COMPILED_IN;
506
        #endif
507
            break;
508
        case KYBER1024:
509
        #ifndef WOLFSSL_KYBER1024
510
            /* Code not compiled in for Kyber-1024. */
511
            ret = NOT_COMPILED_IN;
512
        #endif
513
            break;
514
    #endif
515
0
        case WC_ML_KEM_TYPE_UNSET:
516
            /* Caller will let a DER decode name the parameter set. */
517
0
            break;
518
0
        default:
519
            /* No other values supported. */
520
0
            ret = BAD_FUNC_ARG;
521
0
            break;
522
0
        }
523
0
    }
524
0
    if (ret == 0) {
525
        /* Keep type for parameters. */
526
0
        key->type = type;
527
        /* Cache heap pointer. */
528
0
        key->heap = heap;
529
    #ifdef WOLF_CRYPTO_CB
530
        key->devCtx = NULL;
531
        key->devId = devId;
532
    #endif
533
#ifdef WOLF_PRIVATE_KEY_ID
534
        key->idLen = 0;
535
        key->labelLen = 0;
536
#endif
537
        /* A zeroed object reads as WC_ML_KEM_512, so record the difference
538
         * here rather than inferring it from the type. */
539
0
        key->flags = (type == WC_ML_KEM_TYPE_UNSET) ? 0 : MLKEM_FLAG_TYPE_SET;
540
    #ifdef WC_MLKEM_NONBLOCK
541
        key->nb = NULL;
542
    #endif
543
544
    #ifdef WOLFSSL_MLKEM_DYNAMIC_KEYS
545
        key->priv = NULL;
546
        key->pub = NULL;
547
        key->privAllocSz = 0;
548
    #ifdef WOLFSSL_MLKEM_CACHE_A
549
        key->a = NULL;
550
    #endif
551
    #endif
552
553
        /* Zero out the PRF object. */
554
0
        XMEMSET(&key->prf, 0, sizeof(key->prf));
555
556
        /* Initialize the hash algorithm object. */
557
0
        ret = mlkem_hash_new(&key->hash, heap, devId);
558
0
    }
559
0
    if (ret == 0) {
560
        /* Initialize the PRF algorithm object. */
561
0
        ret = mlkem_prf_new(&key->prf, heap, devId);
562
0
    }
563
0
    if (ret == 0) {
564
0
        mlkem_init();
565
0
    }
566
567
0
    (void)devId;
568
569
0
    return ret;
570
0
}
571
572
#ifdef WOLF_PRIVATE_KEY_ID
573
/**
574
 * Initialize the ML-KEM key with an id.
575
 *
576
 * @param  [out]  key    ML-KEM key object to initialize.
577
 * @param  [in]   type   Type of key:
578
 *                         WC_ML_KEM_512, WC_ML_KEM_768, WC_ML_KEM_1024,
579
 *                         KYBER512, KYBER768, KYBER1024.
580
 * @param  [in]   id     Identifier of key.
581
 * @param  [in]   len    Length of key identifier in bytes.
582
 * @param  [in]   heap   Dynamic memory hint.
583
 * @param  [in]   devId  Device Id.
584
 * @return  0 on success.
585
 * @return  BAD_FUNC_ARG when key is NULL, id is NULL but len is not zero, or
586
 *          type is unrecognized.
587
 * @return  BUFFER_E when len is out of range.
588
 * @return  NOT_COMPILED_IN when key type is not supported.
589
 */
590
int wc_MlKemKey_Init_Id(MlKemKey* key, int type, const unsigned char* id,
591
    int len, void* heap, int devId)
592
{
593
    int ret = 0;
594
595
    /* Validate parameters. */
596
    if ((key == NULL) || (id == NULL && len != 0)) {
597
        ret = BAD_FUNC_ARG;
598
    }
599
    if ((ret == 0) && ((len < 0) || (len > MLKEM_MAX_ID_LEN))) {
600
        ret = BUFFER_E;
601
    }
602
603
    if (ret == 0) {
604
        /* Initialize key. */
605
        ret = wc_MlKemKey_Init(key, type, heap, devId);
606
    }
607
    if ((ret == 0) && (id != NULL) && (len != 0)) {
608
        /* Store key identifier. */
609
        XMEMCPY(key->id, id, (size_t)len);
610
        key->idLen = len;
611
    }
612
613
    return ret;
614
}
615
616
/**
617
 * Initialize the ML-KEM key with a label.
618
 *
619
 * @param  [out]  key    ML-KEM key object to initialize.
620
 * @param  [in]   type   Type of key:
621
 *                         WC_ML_KEM_512, WC_ML_KEM_768, WC_ML_KEM_1024,
622
 *                         KYBER512, KYBER768, KYBER1024.
623
 * @param  [in]   label  Label of key. Must be a null-terminated string.
624
 * @param  [in]   heap   Dynamic memory hint.
625
 * @param  [in]   devId  Device Id.
626
 * @return  0 on success.
627
 * @return  BAD_FUNC_ARG when key or label is NULL, or type is unrecognized.
628
 * @return  BUFFER_E when label is too small or big.
629
 * @return  NOT_COMPILED_IN when key type is not supported.
630
 */
631
int wc_MlKemKey_Init_Label(MlKemKey* key, int type, const char* label,
632
    void* heap, int devId)
633
{
634
    int ret = 0;
635
    int labelLen = 0;
636
637
    /* Validate parameters. */
638
    if ((key == NULL) || (label == NULL)) {
639
        ret = BAD_FUNC_ARG;
640
    }
641
    if (ret == 0) {
642
        /* Validate label length. */
643
        labelLen = (int)XSTRLEN(label);
644
        if ((labelLen == 0) || (labelLen > MLKEM_MAX_LABEL_LEN)) {
645
            ret = BUFFER_E;
646
        }
647
    }
648
649
    if (ret == 0) {
650
        /* Initialize key. */
651
        ret = wc_MlKemKey_Init(key, type, heap, devId);
652
    }
653
    if (ret == 0) {
654
        /* Don't save string in key->label with null terminator.
655
         * Use key->labelLen to get the length if required. */
656
        XMEMCPY(key->label, label, (size_t)labelLen);
657
        key->labelLen = labelLen;
658
    }
659
660
    return ret;
661
}
662
#endif
663
664
/**
665
 * Free the ML-KEM key object.
666
 *
667
 * @param  [in, out]  key   ML-KEM key object to dispose of.
668
 * @return  0 on success.
669
 */
670
int wc_MlKemKey_Free(MlKemKey* key)
671
0
{
672
0
    if (key != NULL) {
673
#if defined(WOLF_CRYPTO_CB) && defined(WOLF_CRYPTO_CB_FREE)
674
        if (key->devId != INVALID_DEVID) {
675
            (void)wc_CryptoCb_Free(key->devId, WC_ALGO_TYPE_PK,
676
                WC_PK_TYPE_PQC_KEM_KEYGEN, WC_PQC_KEM_TYPE_MLKEM, (void*)key);
677
            /* always continue to software cleanup */
678
        }
679
#endif
680
        /* Dispose of PRF object. */
681
0
        mlkem_prf_free(&key->prf);
682
        /* Dispose of hash object. */
683
0
        mlkem_hash_free(&key->hash);
684
        /* Ensure all private data is zeroed. */
685
0
        ForceZero(&key->hash, sizeof(key->hash));
686
0
        ForceZero(&key->prf, sizeof(key->prf));
687
#ifdef WOLF_CRYPTO_CB
688
        key->hash.devId = INVALID_DEVID;
689
        key->prf.devId = INVALID_DEVID;
690
#endif
691
#ifdef WOLFSSL_MLKEM_DYNAMIC_KEYS
692
        if (key->priv != NULL) {
693
            ForceZero(key->priv, key->privAllocSz);
694
            XFREE(key->priv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
695
            key->priv = NULL;
696
            key->privAllocSz = 0;
697
        }
698
        if (key->pub != NULL) {
699
            XFREE(key->pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
700
            key->pub = NULL;
701
        }
702
    #ifdef WOLFSSL_MLKEM_CACHE_A
703
        if (key->a != NULL) {
704
            XFREE(key->a, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
705
            key->a = NULL;
706
        }
707
    #endif
708
#else
709
0
        ForceZero(key->priv, sizeof(key->priv));
710
0
#endif
711
0
        ForceZero(key->z, sizeof(key->z));
712
713
        /* Clear flags as values are no longer set. */
714
0
        key->flags = 0;
715
#ifdef WC_MLKEM_NONBLOCK
716
        /* An operation abandoned mid-flight must not leak its scratch. */
717
        mlkemkey_nb_release(key);
718
        key->nb = NULL;
719
#endif
720
#ifdef WOLF_CRYPTO_CB
721
        /* Mark the key as having no device so a second free does not call
722
         * out to it again. */
723
        key->devCtx = NULL;
724
        key->devId = INVALID_DEVID;
725
#endif
726
0
    }
727
728
0
    return 0;
729
0
}
730
731
#ifdef WC_MLKEM_NONBLOCK
732
/* Release whatever an in-flight non-blocking operation left in the attached
733
 * context and reset it, so an abandoned operation neither leaks nor leaves
734
 * secret material behind. */
735
static void mlkemkey_nb_release(MlKemKey* key)
736
{
737
    wc_MlKemNonBlock* nb = key->nb;
738
739
    if (nb != NULL) {
740
        if (nb->work != NULL) {
741
            ForceZero(nb->work, nb->workSz);
742
            XFREE(nb->work, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
743
        }
744
        if (nb->decWork != NULL) {
745
            ForceZero(nb->decWork, nb->decWorkSz);
746
            XFREE(nb->decWork, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
747
        }
748
        ForceZero(nb, sizeof(*nb));
749
    }
750
}
751
752
/* Claim the context for an operation.
753
 *
754
 * The operation resumes when the context is in flight on the same operation,
755
 * cipher text buffer and bound value. Otherwise whatever another operation
756
 * left behind is released and the context starts this one.
757
 *
758
 * @param [in, out] key   ML-KEM key.
759
 * @param [in]      op    Operation: MLKEM_NB_OP_*.
760
 * @param [in]      bind  Value the operation is bound to. NULL when sz is 0.
761
 * @param [in]      sz    Size of the value in bytes.
762
 * @param [in]      arg   Cipher text buffer of the operation, or NULL.
763
 * @return  1 when the operation is starting, 0 when it resumes or there is
764
 *          no context.
765
 */
766
static int mlkemkey_nb_begin(MlKemKey* key, byte op, const byte* bind,
767
    word32 sz, const void* arg)
768
{
769
    wc_MlKemNonBlock* nb = key->nb;
770
    int fresh = 0;
771
772
    if ((nb != NULL) && ((nb->op != op) || (nb->arg != arg) ||
773
            ((sz != 0) && (ConstantCompare(nb->rand, bind, (int)sz) != 0)))) {
774
        mlkemkey_nb_release(key);
775
        nb->op = op;
776
        nb->arg = arg;
777
        if (sz != 0) {
778
            XMEMCPY(nb->rand, bind, sz);
779
        }
780
        fresh = 1;
781
    }
782
783
    return fresh;
784
}
785
786
/* Attach a non-blocking context to the key, or clear it with nb == NULL. While
787
 * set, MakeKey/Encapsulate/Decapsulate run one chunk per call and return
788
 * MP_WOULDBLOCK until the operation completes. The context is owned by the
789
 * caller and must outlive the operation. Attaching, clearing or freeing the
790
 * key abandons any operation still in flight on the current context, as do
791
 * starting another operation and decoding a key into the key. Decoding a
792
 * private key always runs to completion. */
793
int wc_MlKemKey_set_nonblock(MlKemKey* key, wc_MlKemNonBlock* nb)
794
{
795
    int ret = 0;
796
797
    if (key == NULL) {
798
        ret = BAD_FUNC_ARG;
799
    }
800
    else {
801
        mlkemkey_nb_release(key);
802
        if (nb != NULL) {
803
            XMEMSET(nb, 0, sizeof(*nb));
804
        }
805
        key->nb = nb;
806
    }
807
808
    return ret;
809
}
810
#endif /* WC_MLKEM_NONBLOCK */
811
812
#if !defined(WOLF_CRYPTO_CB_ONLY_MLKEM) && \
813
    (!defined(WOLFSSL_MLKEM_NO_MAKE_KEY) || \
814
     !defined(WOLFSSL_MLKEM_NO_ENCAPSULATE) || \
815
     !defined(WOLFSSL_MLKEM_NO_DECAPSULATE))
816
/* Destroy operation intermediates without losing the reusable hash object
817
 * configuration (FIPS 203 section 3.3). */
818
static void mlkemkey_hash_wipe(wc_Sha3* h)
819
0
{
820
0
#ifndef PSOC6_HASH_SHA3
821
0
    ForceZero(h->s, sizeof(h->s));
822
0
    ForceZero(h->t, sizeof(h->t));
823
0
    h->i = 0;
824
#else
825
    if (wc_Sha3_256_Reset(h) != 0)
826
        WOLFSSL_MSG("ML-KEM hash wipe failed");
827
#endif
828
0
}
829
830
#ifdef WOLFSSL_CHECK_MEM_ZERO
831
/* Register the hash and PRF state that mlkemkey_hash_wipe() must clear. */
832
static void mlkemkey_hash_memzero_add(MlKemKey* key)
833
{
834
#ifndef PSOC6_HASH_SHA3
835
    wc_MemZero_Add("mlkem key hash s", key->hash.s, sizeof(key->hash.s));
836
    wc_MemZero_Add("mlkem key hash t", key->hash.t, sizeof(key->hash.t));
837
    wc_MemZero_Add("mlkem key prf s", key->prf.s, sizeof(key->prf.s));
838
    wc_MemZero_Add("mlkem key prf t", key->prf.t, sizeof(key->prf.t));
839
#else
840
    (void)key;
841
#endif
842
}
843
844
static void mlkemkey_hash_memzero_check(MlKemKey* key)
845
{
846
#ifndef PSOC6_HASH_SHA3
847
    wc_MemZero_Check(key->hash.s, sizeof(key->hash.s));
848
    wc_MemZero_Check(key->hash.t, sizeof(key->hash.t));
849
    wc_MemZero_Check(key->prf.s, sizeof(key->prf.s));
850
    wc_MemZero_Check(key->prf.t, sizeof(key->prf.t));
851
#else
852
    (void)key;
853
#endif
854
}
855
#endif
856
#endif
857
858
/******************************************************************************/
859
860
#ifndef WOLFSSL_MLKEM_NO_MAKE_KEY
861
/**
862
 * Make a ML-KEM key object using a random number generator.
863
 *
864
 * FIPS 203 - Algorithm 19: ML-KEM.KeyGen()
865
 * Generates an encapsulation key and a corresponding decapsulation key.
866
 *   1: d <- B_32                                        >  d is 32 random bytes
867
 *   2: z <- B_32                                        >  z is 32 random bytes
868
 *   3: if d == NULL or z == NULL then
869
 *   4:   return falsum
870
 *                  > return an error indication if random bit generation failed
871
 *   5: end if
872
 *   6: (ek,dk) <- ML-KEM.KeyGen_Internal(d, z)
873
 *                                       > run internal key generation algorithm
874
 *   7: return (ek,dk)
875
 *
876
 * @param  [in, out]  key   ML-KEM key object.
877
 * @param  [in]       rng   Random number generator.
878
 * @return  0 on success.
879
 * @return  BAD_FUNC_ARG when key or rng is NULL.
880
 * @return  MEMORY_E when dynamic memory allocation failed.
881
 * @return  RNG_FAILURE_E when generating random numbers failed.
882
 * @return  DRBG_CONT_FAILURE when random number generator health check fails.
883
 * @return  ML_KEM_PCT_E when pairwise consistency test fails. FIPS only.
884
 * @return  BAD_COND_E when fault attack detected.
885
 * @return  NOT_COMPILED_IN when no random number generator is compiled in or
886
 *          key type is not supported.
887
 */
888
int wc_MlKemKey_MakeKey(MlKemKey* key, WC_RNG* rng)
889
0
{
890
0
#ifndef WC_NO_RNG
891
0
    int ret = 0;
892
0
    unsigned char rand[WC_ML_KEM_MAKEKEY_RAND_SZ];
893
#ifdef WC_CRYPTOCB_KEYGEN_ID_CHECK
894
    int idKey = 0;
895
    int idDevId = INVALID_DEVID;
896
#endif
897
898
    /* Validate parameters. */
899
0
    if ((key == NULL) || (rng == NULL)) {
900
0
        ret = BAD_FUNC_ARG;
901
0
    }
902
903
#ifdef WC_CRYPTOCB_KEYGEN_ID_CHECK
904
    if (ret == 0) {
905
        idKey = WC_CRYPTOCB_HAS_ID(key);
906
        idDevId = key->devId;
907
    }
908
#endif
909
#ifdef WOLF_CRYPTO_CB
910
#ifndef WOLF_CRYPTO_CB_FIND
911
    if ((ret == 0) && (key->devId != INVALID_DEVID)) {
912
#else
913
    if (ret == 0) {
914
#endif
915
        ret = wc_CryptoCb_MakePqcKemKey(rng, WC_PQC_KEM_TYPE_MLKEM, key->type,
916
            key);
917
        if (ret == WC_NO_ERR_TRACE(WC_PENDING_E))
918
            ret = BAD_STATE_E; /* async unsupported for KEM keygen */
919
        if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE))
920
            return ret;
921
        /* fall-through when unavailable */
922
        ret = 0;
923
    }
924
#ifdef WC_CRYPTOCB_KEYGEN_ID_CHECK
925
    if ((ret == 0) && idKey && wc_CryptoCb_HasPkDevice(idDevId)) {
926
        ret = NO_VALID_DEVID;
927
    }
928
#endif
929
#endif
930
931
0
    if (ret == 0) {
932
#ifdef WC_MLKEM_NONBLOCK
933
        if ((key->nb != NULL) && (key->nb->op == MLKEM_NB_OP_MAKE) &&
934
                key->nb->fromRng) {
935
            /* Resume: reuse the seeds drawn on the first call so each resumed
936
             * phase derives the same key. Only a generation started here: one
937
             * started from a caller's seeds is not this operation. */
938
            XMEMCPY(rand, key->nb->rand, sizeof(rand));
939
        }
940
        else
941
#endif
942
0
        {
943
        /* Generate random to use with PRFs.
944
         * Step 1: d is 32 random bytes
945
         * Step 2: z is 32 random bytes
946
         */
947
0
        ret = wc_RNG_GenerateBlock(rng, rand, WC_ML_KEM_SYM_SZ * 2);
948
0
        }
949
        /* Step 3: ret is not zero when d == NULL or z == NULL. */
950
        /* rand now holds the secret seeds d||z; register before key gen /
951
         * PCT so any future early-exit before the ForceZero is caught. */
952
#ifdef WOLFSSL_CHECK_MEM_ZERO
953
        wc_MemZero_Add("mlkem makekey rand", (void*)rand, (word32)sizeof(rand));
954
#endif
955
0
    }
956
0
    if (ret == 0) {
957
        /* Make a key pair from the random.
958
         * Step 6. run internal key generation algorithm
959
         * Step 7. public and private key are stored in key
960
         */
961
0
        ret = wc_MlKemKey_MakeKeyWithRandom(key, rand, sizeof(rand));
962
#ifdef WC_MLKEM_NONBLOCK
963
        if ((key->nb != NULL) && (ret == WC_NO_ERR_TRACE(MP_WOULDBLOCK))) {
964
            key->nb->fromRng = 1;
965
        }
966
#endif
967
0
    }
968
969
    /* No key-pair test here: wc_MlKemKey_MakeKeyWithRandom(), called above,
970
     * runs it whenever the build tests new key pairs. */
971
972
    /* Ensure seeds are zeroized. */
973
0
    ForceZero((void*)rand, (word32)sizeof(rand));
974
#ifdef WOLFSSL_CHECK_MEM_ZERO
975
    wc_MemZero_Check((void*)rand, (word32)sizeof(rand));
976
#endif
977
978
    /* Step 4: return ret != 0 on falsum or internal key generation failure. */
979
0
    return ret;
980
#else
981
    (void)key;
982
    (void)rng;
983
    return NOT_COMPILED_IN;
984
#endif /* WC_NO_RNG */
985
0
}
986
987
/**
988
 * Make a ML-KEM key object using random data.
989
 *
990
 * FIPS 203 - Algorithm 16: ML-KEM.KeyGen_internal(d,z)
991
 * Uses randomness to generate an encapsulation key and a corresponding
992
 * decapsulation key.
993
 *   1: (ek_PKE,dk_PKE) <- K-PKE.KeyGen(d)        > run key generation for K-PKE
994
 *   ...
995
 *
996
 * FIPS 203 - Algorithm 13: K-PKE.KeyGen(d)
997
 * Uses randomness to generate an encryption key and a corresponding decryption
998
 * key.
999
 *   1: (rho,sigma) <- G(d||k)
1000
 *                         > expand 32+1 bytes to two pseudorandom 32-byte seeds
1001
 *   2: N <- 0
1002
 *   3-7: generate matrix A_hat
1003
 *   8-11: generate s
1004
 *   12-15: generate e
1005
 *   16-18: calculate t_hat from A_hat, s and e
1006
 *   ...
1007
 *
1008
 * @param  [in, out]  key   ML-KEM key object.
1009
 * @param  [in]       rand  Random data.
1010
 * @param  [in]       len   Length of random data in bytes.
1011
 * @return  0 on success.
1012
 * @return  BAD_FUNC_ARG when key or rand is NULL.
1013
 * @return  BUFFER_E when length is not WC_ML_KEM_MAKEKEY_RAND_SZ.
1014
 * @return  NOT_COMPILED_IN when key type is not supported.
1015
 * @return  MEMORY_E when dynamic memory allocation failed.
1016
 * @return  BAD_COND_E when fault attack detected.
1017
 * @return  ML_KEM_PCT_E when the key pair fails its consistency test.  On
1018
 *          any error from that test the key is freed and must be
1019
 *          re-initialised before reuse.
1020
 */
1021
int wc_MlKemKey_MakeKeyWithRandom(MlKemKey* key, const unsigned char* rand,
1022
    int len)
1023
0
{
1024
#ifdef WOLF_CRYPTO_CB_ONLY_MLKEM
1025
    /* Validate as the software path does, so the reported error stays the
1026
     * same for a bad call. */
1027
    if ((key == NULL) || (rand == NULL)) {
1028
        return BAD_FUNC_ARG;
1029
    }
1030
    if (len != WC_ML_KEM_MAKEKEY_RAND_SZ) {
1031
        return BUFFER_E;
1032
    }
1033
    return NO_VALID_DEVID;
1034
#else
1035
0
    byte buf[2 * WC_ML_KEM_SYM_SZ + 1];
1036
0
    byte* rho = buf;
1037
0
#ifndef WC_MLKEM_FAULT_HARDEN
1038
0
    byte* sigma = buf + WC_ML_KEM_SYM_SZ;
1039
#else
1040
    byte sigma[WC_ML_KEM_SYM_SZ + 1];
1041
#endif
1042
0
#ifndef WOLFSSL_NO_MALLOC
1043
0
    sword16* e = NULL;
1044
#else
1045
#ifndef WOLFSSL_MLKEM_MAKEKEY_SMALL_MEM
1046
#ifndef WOLFSSL_MLKEM_CACHE_A
1047
    sword16 e[(WC_ML_KEM_MAX_K + 1) * WC_ML_KEM_MAX_K * MLKEM_N];
1048
#else
1049
    sword16 e[WC_ML_KEM_MAX_K * MLKEM_N];
1050
#endif
1051
#else
1052
    /* Small memory generation only holds one polynomial at a time. */
1053
    sword16 e[MLKEM_N];
1054
#endif
1055
#endif
1056
    /* Matrix A. NULL when it is streamed and not kept. */
1057
0
    sword16* a = NULL;
1058
0
    sword16* s = NULL;
1059
0
    sword16* t = NULL;
1060
    /* Number of bytes of e holding secret noise, to be zeroized. */
1061
0
    size_t eSz = 0;
1062
0
    int ret = 0;
1063
0
    int k = 0;
1064
1065
#ifdef WOLFSSL_CHECK_MEM_ZERO
1066
    /* buf is only conditionally filled by G() below; define it on all paths so
1067
     * the later registration/Check are safe. */
1068
    XMEMSET(buf, 0, sizeof(buf));
1069
#endif
1070
1071
    /* Validate parameters. */
1072
0
    if ((key == NULL) || (rand == NULL)) {
1073
0
        ret = BAD_FUNC_ARG;
1074
0
    }
1075
0
    if ((ret == 0) && (len != WC_ML_KEM_MAKEKEY_RAND_SZ)) {
1076
0
        ret = BUFFER_E;
1077
0
    }
1078
#ifdef WC_MLKEM_NONBLOCK
1079
    if (ret == 0) {
1080
        /* Resume only the generation from these seeds. */
1081
        if (mlkemkey_nb_begin(key, MLKEM_NB_OP_MAKE, rand,
1082
                WC_ML_KEM_MAKEKEY_RAND_SZ, NULL) == 1) {
1083
            WOLFSSL_MSG("ML-KEM non-blocking make key starting");
1084
        } else {
1085
            WOLFSSL_MSG("ML-KEM non-blocking make key resuming or unset");
1086
        }
1087
    }
1088
#endif
1089
1090
0
    if (ret == 0) {
1091
0
        int hadPriv = (key->flags & MLKEM_FLAG_PRIV_SET) != 0;
1092
1093
        /* Discards the key material, not the parameter set. */
1094
0
        key->flags &= MLKEM_FLAG_TYPE_SET;
1095
1096
        /* Establish parameters based on key type. */
1097
0
        k = mlkemkey_get_k(key);
1098
#ifdef WOLFSSL_CHECK_MEM_ZERO
1099
        if (k != 0) {
1100
            mlkemkey_hash_memzero_add(key);
1101
        }
1102
#endif
1103
0
        if (k == 0) {
1104
0
            ret = NOT_COMPILED_IN;
1105
0
        }
1106
0
        else {
1107
0
#ifndef WOLFSSL_MLKEM_MAKEKEY_SMALL_MEM
1108
0
            eSz = (size_t)(k * MLKEM_N) * sizeof(sword16);
1109
#else
1110
            eSz = (size_t)MLKEM_N * sizeof(sword16);
1111
#endif
1112
0
        }
1113
0
        if ((ret == 0) && hadPriv) {
1114
            /* Do not write the new key over the old one. */
1115
0
#ifndef WOLFSSL_MLKEM_DYNAMIC_KEYS
1116
0
            ForceZero(key->priv, (size_t)k * MLKEM_N * sizeof(sword16));
1117
0
#endif
1118
0
            ForceZero(key->z, sizeof(key->z));
1119
0
        }
1120
0
    }
1121
1122
0
#ifndef WOLFSSL_NO_MALLOC
1123
0
    if (ret == 0) {
1124
        /* Allocate dynamic memory for matrix and error vector. */
1125
0
#ifndef WOLFSSL_MLKEM_MAKEKEY_SMALL_MEM
1126
0
#ifndef WOLFSSL_MLKEM_CACHE_A
1127
        /* e (v) | a (m) */
1128
0
        e = (sword16*)XMALLOC((size_t)((k + 1) * k * MLKEM_N) * sizeof(sword16),
1129
0
            key->heap, DYNAMIC_TYPE_TMP_BUFFER);
1130
#else
1131
        /* e (v) */
1132
        e = (sword16*)XMALLOC((size_t)(k * MLKEM_N) * sizeof(sword16),
1133
            key->heap, DYNAMIC_TYPE_TMP_BUFFER);
1134
#endif
1135
#else
1136
        /* e (p) - matrix A is generated a polynomial at a time into it. */
1137
    #ifdef WC_MLKEM_NONBLOCK
1138
        if ((key->nb != NULL) && (key->nb->work != NULL)) {
1139
            /* Resume: reuse the noise scratch from the previous call. */
1140
            e = (sword16*)key->nb->work;
1141
        }
1142
        else
1143
    #endif
1144
        {
1145
            e = (sword16*)XMALLOC(eSz, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
1146
        #ifdef WC_MLKEM_NONBLOCK
1147
            if ((e != NULL) && (key->nb != NULL)) {
1148
                key->nb->work = e;
1149
                key->nb->workSz = (word32)eSz;
1150
            }
1151
        #endif
1152
        }
1153
#endif
1154
0
        if (e == NULL) {
1155
0
            ret = MEMORY_E;
1156
0
        }
1157
0
    }
1158
0
#endif
1159
#ifdef WOLFSSL_MLKEM_DYNAMIC_KEYS
1160
    /* The allocators discard what the buffers hold, so a resumed non-blocking
1161
     * call must keep the vectors the first call allocated. */
1162
#ifdef WC_MLKEM_NONBLOCK
1163
    if ((ret == 0) && ((key->nb == NULL) || (key->nb->state == 0)))
1164
#else
1165
    if (ret == 0)
1166
#endif
1167
    {
1168
        ret = mlkemkey_alloc_priv(key, (unsigned int)k);
1169
        if (ret == 0) {
1170
            ret = mlkemkey_alloc_pub(key, (unsigned int)k);
1171
        }
1172
#ifdef WOLFSSL_MLKEM_CACHE_A
1173
        if (ret == 0) {
1174
            ret = mlkemkey_alloc_a(key, (unsigned int)k);
1175
        }
1176
#endif
1177
    }
1178
#endif
1179
0
    if (ret == 0) {
1180
0
        const byte* d = rand;
1181
1182
#ifdef WOLFSSL_MLKEM_CACHE_A
1183
        a = key->a;
1184
#elif !defined(WOLFSSL_MLKEM_MAKEKEY_SMALL_MEM)
1185
        /* Matrix A allocated at end of error vector. */
1186
0
        a = e + (k * MLKEM_N);
1187
0
#endif
1188
1189
#if defined(WOLFSSL_MLKEM_KYBER) && !defined(WOLFSSL_NO_ML_KEM)
1190
        if (key->type & MLKEM_KYBER)
1191
#endif
1192
#ifdef WOLFSSL_MLKEM_KYBER
1193
        {
1194
            /* Expand 32 bytes of random to 64. */
1195
            ret = MLKEM_HASH_G(&key->hash, d, WC_ML_KEM_SYM_SZ, NULL, 0, buf);
1196
        }
1197
#endif
1198
#if defined(WOLFSSL_MLKEM_KYBER) && !defined(WOLFSSL_NO_ML_KEM)
1199
        else
1200
#endif
1201
0
#ifndef WOLFSSL_NO_ML_KEM
1202
0
        {
1203
0
            buf[0] = (byte)k;
1204
            /* Expand 33 bytes of random to 64.
1205
             * Alg 13: Step 1: (rho,sigma) <- G(d||k)
1206
             */
1207
0
            ret = MLKEM_HASH_G(&key->hash, d, WC_ML_KEM_SYM_SZ, buf, 1, buf);
1208
0
        }
1209
0
#endif
1210
0
    }
1211
#ifdef WC_MLKEM_FAULT_HARDEN
1212
    if (ret == 0) {
1213
        XMEMCPY(sigma, buf + WC_ML_KEM_SYM_SZ, WC_ML_KEM_SYM_SZ);
1214
        /* sigma now holds the secret noise seed; register it (FAULT_HARDEN
1215
         * build only, where sigma is its own stack buffer). */
1216
#ifdef WOLFSSL_CHECK_MEM_ZERO
1217
        wc_MemZero_Add("mlkem keygen sigma", sigma, sizeof(sigma));
1218
#endif
1219
        /* Check that correct data was copied and pointer was not faulted. */
1220
        if (XMEMCMP(sigma, rho, WC_ML_KEM_SYM_SZ) == 0) {
1221
            ret = BAD_COND_E;
1222
        }
1223
        /* Check that sigma is after rho - rho pointer may have been modified.
1224
         */
1225
        if (XMEMCMP(sigma, rho + WC_ML_KEM_SYM_SZ, WC_ML_KEM_SYM_SZ) != 0) {
1226
            ret = BAD_COND_E;
1227
        }
1228
    }
1229
#endif
1230
    /* buf holds rho||sigma; sigma is the secret noise seed. Now that G() has
1231
     * filled it, register buf before key generation so any later exit before
1232
     * the ForceZero is covered. */
1233
#ifdef WOLFSSL_CHECK_MEM_ZERO
1234
    wc_MemZero_Add("mlkem keygen buf", buf, sizeof(buf));
1235
#endif
1236
0
    if (ret == 0) {
1237
0
        const byte* z = rand + WC_ML_KEM_SYM_SZ;
1238
0
        s = key->priv;
1239
0
        t = key->pub;
1240
1241
        /* Cache the public seed for use in encapsulation and encoding public
1242
         * key. */
1243
0
        XMEMCPY(key->pubSeed, rho, WC_ML_KEM_SYM_SZ);
1244
        /* Cache the z value for decapsulation and encoding private key. */
1245
0
        XMEMCPY(key->z, z, sizeof(key->z));
1246
1247
        /* Initialize PRF for use in noise generation. */
1248
0
        ret = mlkem_prf_reset(&key->prf);
1249
0
    }
1250
0
    if (ret == 0) {
1251
0
#ifndef WOLFSSL_MLKEM_MAKEKEY_SMALL_MEM
1252
        /* Generate noise using PRF.
1253
         * Alg 13: Steps 8-15: generate s and e
1254
         */
1255
0
        ret = mlkem_get_noise(&key->prf, k, s, e, NULL, sigma);
1256
0
    }
1257
0
    if (ret == 0) {
1258
        /* Generate the matrix A.
1259
         * Alg 13: Steps 3-7
1260
         */
1261
0
        ret = mlkem_gen_matrix(&key->prf, a, k, rho, 0);
1262
0
    }
1263
0
    if (ret == 0) {
1264
        /* Generate key pair from random data.
1265
         * Alg 13: Steps 16-18.
1266
         */
1267
0
        ret = mlkem_keygen(s, t, e, a, k);
1268
0
    }
1269
0
    if (ret == 0) {
1270
#else
1271
        /* Generate noise s (Alg 13 Steps 8-11) and NTT it (Step 16). Both run
1272
         * once; a non-blocking resume must not repeat them - get_noise would
1273
         * overwrite s (key->priv) and the NTT would be applied twice. */
1274
#ifdef WC_MLKEM_NONBLOCK
1275
        if ((key->nb == NULL) || (key->nb->state == 0))
1276
#endif
1277
        {
1278
            ret = mlkem_get_noise(&key->prf, k, s, NULL, NULL, sigma);
1279
            if (ret == 0) {
1280
                mlkem_keygen_ntt_priv(s, k);
1281
            }
1282
#ifdef WC_MLKEM_NONBLOCK
1283
            if ((ret == 0) && (key->nb != NULL)) {
1284
                /* Yield after the prelude; the per-row loop resumes below. */
1285
                key->nb->state = 1;
1286
                key->nb->row = 0;
1287
                ret = MP_WOULDBLOCK;
1288
            }
1289
#endif
1290
        }
1291
    }
1292
    if (ret == 0) {
1293
        /* Generate the public vector t one row at a time from A_hat, s_hat and
1294
         * e. Alg 13 Steps 3-7, 12-15, 17-18. s is already NTT transformed; t
1295
         * (key->pub) and s (key->priv) carry the result across yields. */
1296
        int i;
1297
        int i0 = 0;
1298
#ifdef WC_MLKEM_NONBLOCK
1299
        if (key->nb != NULL) {
1300
            i0 = key->nb->row;
1301
        }
1302
#endif
1303
        for (i = i0; (ret == 0) && (i < k); i++) {
1304
            ret = mlkem_keygen_seeds_row(s, t, &key->prf, e, a, k, rho, sigma,
1305
                i);
1306
#ifdef WC_MLKEM_NONBLOCK
1307
            /* Yield per row so one slice is about a single row's work. */
1308
            if ((key->nb != NULL) && (ret == 0) && (i + 1 < k)) {
1309
                key->nb->row = (word16)(i + 1);
1310
                ret = MP_WOULDBLOCK;
1311
            }
1312
#endif
1313
        }
1314
        if ((ret != 0)
1315
#ifdef WC_MLKEM_NONBLOCK
1316
            && (ret != WC_NO_ERR_TRACE(MP_WOULDBLOCK))
1317
#endif
1318
            ) {
1319
            ForceZero(t, (size_t)k * MLKEM_N * sizeof(sword16));
1320
        }
1321
    }
1322
    if (ret == 0) {
1323
#endif
1324
        /* Private and public key are set/available. */
1325
0
        key->flags |= MLKEM_FLAG_PRIV_SET | MLKEM_FLAG_PUB_SET;
1326
#ifdef WOLFSSL_MLKEM_CACHE_A
1327
        key->flags |= MLKEM_FLAG_A_SET;
1328
#endif
1329
0
    }
1330
0
    else if ((key != NULL) && (k != 0)
1331
#ifdef WC_MLKEM_NONBLOCK
1332
             && (ret != WC_NO_ERR_TRACE(MP_WOULDBLOCK))
1333
#endif
1334
0
             ) {
1335
        /* Keygen failed after s and z were written; k is 0 until the
1336
         * argument checks passed (ISO/IEC 19790:2012 7.9.7). A non-blocking
1337
         * yield is not a failure, so it must not wipe the partial key. */
1338
#ifdef WOLFSSL_MLKEM_DYNAMIC_KEYS
1339
        if (key->priv != NULL) {
1340
            ForceZero(key->priv, key->privAllocSz);
1341
        }
1342
#else
1343
0
        ForceZero(key->priv, sizeof(key->priv));
1344
0
#endif
1345
0
        ForceZero(key->z, sizeof(key->z));
1346
0
    }
1347
1348
    /* Zeroize the secret seed material in rho||sigma (sigma) before return. */
1349
0
    ForceZero(buf, sizeof(buf));
1350
#ifdef WOLFSSL_CHECK_MEM_ZERO
1351
    wc_MemZero_Check(buf, sizeof(buf));
1352
#endif
1353
#ifdef WC_MLKEM_FAULT_HARDEN
1354
    ForceZero(sigma, sizeof(sigma));
1355
#ifdef WOLFSSL_CHECK_MEM_ZERO
1356
    wc_MemZero_Check(sigma, sizeof(sigma));
1357
#endif
1358
#endif
1359
1360
0
#ifndef WOLFSSL_NO_MALLOC
1361
    /* Free dynamic memory allocated in function. */
1362
#ifdef WC_MLKEM_NONBLOCK
1363
    if ((key != NULL) && (key->nb != NULL) &&
1364
            (ret == WC_NO_ERR_TRACE(MP_WOULDBLOCK))) {
1365
        /* Yielding: keep the noise scratch for the next call. */
1366
    }
1367
    else if ((key != NULL) && (key->nb != NULL)) {
1368
        /* Final success or error: release the noise scratch, which the
1369
         * context owns even when this call failed before picking it up, and
1370
         * reset the context. */
1371
        mlkemkey_nb_release(key);
1372
    }
1373
    else
1374
#endif
1375
0
    if (e != NULL) {
1376
0
        ForceZero(e, eSz);
1377
0
        XFREE(e, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
1378
0
    }
1379
#else
1380
    /* e is a stack buffer holding the secret noise; zeroize it. */
1381
#ifdef WOLFSSL_CHECK_MEM_ZERO
1382
    wc_MemZero_Add("mlkem keygen e", e, eSz);
1383
#endif
1384
    ForceZero(e, eSz);
1385
#ifdef WOLFSSL_CHECK_MEM_ZERO
1386
    wc_MemZero_Check(e, eSz);
1387
#endif
1388
#endif
1389
1390
/* ML-KEM, ML-DSA, SLH-DSA, LMS and XMSS were never FIPS approved before the v7
1391
 * module, so this test stays gated on v7 and must never be widened to plain
1392
 * HAVE_FIPS.  WOLFSSL_VALIDATE_MLKEM_KEYGEN opts a non-FIPS build in, off by
1393
 * default. */
1394
#if FIPS_VERSION3_GE(7,0,0) || defined(WOLFSSL_VALIDATE_MLKEM_KEYGEN)
1395
#if defined(WOLFSSL_MLKEM_NO_ENCAPSULATE) || defined(WOLFSSL_MLKEM_NO_DECAPSULATE)
1396
    #error "ML-KEM key generation needs encapsulate and decapsulate for the \
1397
key-pair test required by ISO/IEC 19790:2012 sec 7.10.3.3"
1398
#endif
1399
    /* Test every new key pair: encapsulate with it, decapsulate with it, and
1400
     * check the shared secrets match.  ISO/IEC 19790:2012 sec 7.10.3.3;
1401
     * FIPS 140-3 IG 10.3.A Additional Comment 1 spells this test out for
1402
     * FIPS 203.  Fixed `m` because this path takes no RNG, and a self-test
1403
     * needs a working round trip, not an unpredictable one. */
1404
    if (ret == 0) {
1405
        WC_DECLARE_VAR(pct_ct, byte, WC_ML_KEM_MAX_CIPHER_TEXT_SIZE,
1406
            key->heap);
1407
        byte pct_ss1[WC_ML_KEM_SS_SZ];
1408
        byte pct_ss2[WC_ML_KEM_SS_SZ];
1409
        word32 pct_ctSz = 0;
1410
        /* Fixed test pattern for the FIPS 203 Alg 17 `m` input; the value is
1411
         * arbitrary - a PCT roundtrip does not require unpredictability. */
1412
        static const byte pct_m[WC_ML_KEM_ENC_RAND_SZ] = {
1413
            0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB,
1414
            0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB,
1415
            0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB,
1416
            0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB
1417
        };
1418
1419
        WC_ALLOC_VAR_EX(pct_ct, byte, WC_ML_KEM_MAX_CIPHER_TEXT_SIZE,
1420
            key->heap, DYNAMIC_TYPE_TMP_BUFFER, ret = MEMORY_E);
1421
1422
        /* Zero and register the shared secrets up front so the leak checker
1423
         * covers them for the whole block. */
1424
#ifdef WOLFSSL_CHECK_MEM_ZERO
1425
        XMEMSET(pct_ss1, 0, sizeof(pct_ss1));
1426
        XMEMSET(pct_ss2, 0, sizeof(pct_ss2));
1427
        wc_MemZero_Add("mlkem pct ss1", pct_ss1, sizeof(pct_ss1));
1428
        wc_MemZero_Add("mlkem pct ss2", pct_ss2, sizeof(pct_ss2));
1429
        /* Register the ciphertext too, so an early exit added later between
1430
         * here and the ForceZero below is caught the same way. */
1431
        if (WC_VAR_OK(pct_ct))
1432
            wc_MemZero_Add("mlkem pct ct", pct_ct,
1433
                WC_ML_KEM_MAX_CIPHER_TEXT_SIZE);
1434
#endif
1435
        if (ret == 0)
1436
            ret = wc_MlKemKey_CipherTextSize(key, &pct_ctSz);
1437
1438
        if (ret == 0)
1439
            ret = wc_MlKemKey_EncapsulateWithRandom(key, pct_ct, pct_ss1,
1440
                pct_m, (int)sizeof(pct_m));
1441
1442
        if (ret == 0)
1443
            ret = wc_MlKemKey_Decapsulate(key, pct_ss2, pct_ct, pct_ctSz);
1444
1445
        if (ret == 0) {
1446
            if (XMEMCMP(pct_ss1, pct_ss2, WC_ML_KEM_SS_SZ) != 0)
1447
                ret = ML_KEM_PCT_E;
1448
        }
1449
1450
        ForceZero(pct_ss1, sizeof(pct_ss1));
1451
        ForceZero(pct_ss2, sizeof(pct_ss2));
1452
#ifdef WOLFSSL_CHECK_MEM_ZERO
1453
        wc_MemZero_Check(pct_ss1, sizeof(pct_ss1));
1454
        wc_MemZero_Check(pct_ss2, sizeof(pct_ss2));
1455
#endif
1456
        if (WC_VAR_OK(pct_ct)) {
1457
            ForceZero(pct_ct, WC_ML_KEM_MAX_CIPHER_TEXT_SIZE);
1458
        #ifdef WOLFSSL_CHECK_MEM_ZERO
1459
            /* Must run before the free, or the registration outlives the
1460
             * allocation. */
1461
            wc_MemZero_Check(pct_ct, WC_ML_KEM_MAX_CIPHER_TEXT_SIZE);
1462
        #endif
1463
        }
1464
1465
        WC_FREE_VAR_EX(pct_ct, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
1466
1467
        /* Free a key that failed or could not finish the test.
1468
         * ISO/IEC 19790:2012 sec 7.10.3.3: every generated key pair is tested. */
1469
        if (ret != 0) {
1470
            int freeRet = wc_MlKemKey_Free(key);
1471
            if (freeRet != 0)
1472
                ret = freeRet;
1473
        }
1474
    }
1475
#endif /* FIPS v7 or WOLFSSL_VALIDATE_MLKEM_KEYGEN */
1476
1477
0
    if ((key != NULL) && (k != 0)) {
1478
0
        mlkemkey_hash_wipe(&key->hash);
1479
0
        mlkemkey_hash_wipe(&key->prf);
1480
    #ifdef WOLFSSL_CHECK_MEM_ZERO
1481
        mlkemkey_hash_memzero_check(key);
1482
    #endif
1483
0
    }
1484
1485
0
    return ret;
1486
0
#endif /* WOLF_CRYPTO_CB_ONLY_MLKEM */
1487
0
}
1488
#endif /* !WOLFSSL_MLKEM_NO_MAKE_KEY */
1489
1490
/******************************************************************************/
1491
1492
/**
1493
 * Get the size in bytes of cipher text for key.
1494
 *
1495
 * @param  [in]   key  ML-KEM key object.
1496
 * @param  [out]  len  Length of cipher text in bytes.
1497
 * @return  0 on success.
1498
 * @return  BAD_FUNC_ARG when key or len is NULL.
1499
 * @return  NOT_COMPILED_IN when key type is not supported.
1500
 */
1501
int wc_MlKemKey_CipherTextSize(MlKemKey* key, word32* len)
1502
0
{
1503
0
    int ret = 0;
1504
1505
    /* Validate parameters. */
1506
0
    if ((key == NULL) || (len == NULL)) {
1507
0
        ret = BAD_FUNC_ARG;
1508
0
    }
1509
1510
0
    if (ret == 0) {
1511
        /* Return in 'len' size of the cipher text for the type of this key. */
1512
0
        switch (key->type) {
1513
0
#ifndef WOLFSSL_NO_ML_KEM
1514
0
    #ifdef WOLFSSL_WC_ML_KEM_512
1515
0
        case WC_ML_KEM_512:
1516
0
            *len = WC_ML_KEM_512_CIPHER_TEXT_SIZE;
1517
0
            break;
1518
0
    #endif
1519
0
    #ifdef WOLFSSL_WC_ML_KEM_768
1520
0
        case WC_ML_KEM_768:
1521
0
            *len = WC_ML_KEM_768_CIPHER_TEXT_SIZE;
1522
0
            break;
1523
0
    #endif
1524
0
    #ifdef WOLFSSL_WC_ML_KEM_1024
1525
0
        case WC_ML_KEM_1024:
1526
0
            *len = WC_ML_KEM_1024_CIPHER_TEXT_SIZE;
1527
0
            break;
1528
0
    #endif
1529
0
#endif
1530
#ifdef WOLFSSL_MLKEM_KYBER
1531
    #ifdef WOLFSSL_KYBER512
1532
        case KYBER512:
1533
            *len = KYBER512_CIPHER_TEXT_SIZE;
1534
            break;
1535
    #endif
1536
    #ifdef WOLFSSL_KYBER768
1537
        case KYBER768:
1538
            *len = KYBER768_CIPHER_TEXT_SIZE;
1539
            break;
1540
    #endif
1541
    #ifdef WOLFSSL_KYBER1024
1542
        case KYBER1024:
1543
            *len = KYBER1024_CIPHER_TEXT_SIZE;
1544
            break;
1545
    #endif
1546
#endif
1547
0
        default:
1548
            /* No other values supported. */
1549
0
            ret = NOT_COMPILED_IN;
1550
0
            break;
1551
0
        }
1552
0
    }
1553
1554
0
    return ret;
1555
0
}
1556
1557
/**
1558
 * Size of a shared secret in bytes. Always WC_ML_KEM_SS_SZ.
1559
 *
1560
 * @param  [in]   key  ML-KEM key object. Not used.
1561
 * @param  [out]  len  Size of the shared secret created with a ML-KEM key.
1562
 * @return  0 on success.
1563
 * @return  BAD_FUNC_ARG when len is NULL.
1564
 */
1565
int wc_MlKemKey_SharedSecretSize(MlKemKey* key, word32* len)
1566
0
{
1567
0
    int ret = 0;
1568
1569
0
    if (len == NULL) {
1570
0
        ret = BAD_FUNC_ARG;
1571
0
    }
1572
0
    else {
1573
0
        *len = WC_ML_KEM_SS_SZ;
1574
0
    }
1575
1576
0
    (void)key;
1577
0
    return ret;
1578
0
}
1579
1580
#if !defined(WOLFSSL_MLKEM_NO_ENCAPSULATE) || \
1581
    !defined(WOLFSSL_MLKEM_NO_DECAPSULATE)
1582
#ifndef WOLF_CRYPTO_CB_ONLY_MLKEM
1583
/* Encrypt a message to cipher text with the encryption key.
1584
 *
1585
 * FIPS 203, Algorithm 14: K-PKE.Encrypt(ek_PKE, m, r)
1586
 * Uses the encryption key to encrypt a plaintext message using the randomness
1587
 * r.
1588
 *   1: N <- 0
1589
 *   2: t_hat <- ByteDecode_12(ek_PKE[0:384k])
1590
 *                                   > run ByteDecode_12 k times to decode t_hat
1591
 *   3: rho <- ek_PKE[384k : 384k + 32]
1592
 *                                            > extract 32-byte seed from ek_PKE
1593
 *   4-8: generate matrix A_hat
1594
 *   9-12: generate y
1595
 *   13-16: generate e_1
1596
 *   17: generate e_2
1597
 *   18-19: calculate u
1598
 *   20: mu <- Decompress_1(ByteDecode_1(m))
1599
 *   21: calculate v
1600
 *   22: c_1 <- ByteEncode_d_u(Compress_d_u(u))
1601
 *                                 > run ByteEncode_d_u and Compress_d_u k times
1602
 *   23: c_2 <- ByteEncode_d_v(Compress_d_v(v))
1603
 *   24: return c <- (c_1||c_2)
1604
 *
1605
 * @param  [in]      key   ML-KEM key object.
1606
 * @param  [in]      m     Random bytes.
1607
 * @param  [in]      r     Seed to feed to PRF when generating y, e1 and e2.
1608
 * @param  [out]     c     Calculated cipher text. Unused when comparing.
1609
 * @param  [in]      cmp   Cipher text to compare against. May be NULL.
1610
 * @param  [out]     fail  Set to 0 on a match and -1 on a mismatch, once every
1611
 *                         block is compared. Only used when cmp is not NULL.
1612
 * @return  0 on success.
1613
 * @return  BAD_FUNC_ARG when cmp is not NULL and comparing is not compiled in.
1614
 * @return  NOT_COMPILED_IN when key type is not supported.
1615
 */
1616
static int mlkemkey_encapsulate(MlKemKey* key, const byte* m, byte* r, byte* c,
1617
    const byte* cmp, int* fail)
1618
0
{
1619
0
    int ret = 0;
1620
0
    sword16* a = NULL;
1621
0
#ifndef WOLFSSL_MLKEM_ENCAPSULATE_SMALL_MEM
1622
0
    sword16* mu = NULL;
1623
0
    sword16* e1 = NULL;
1624
0
    sword16* e2 = NULL;
1625
0
#endif
1626
0
    unsigned int k = 0;
1627
0
    unsigned int compVecSz = 0;
1628
0
#ifndef WOLFSSL_NO_MALLOC
1629
0
    sword16* y = NULL;
1630
0
    size_t yAllocSz = 0;
1631
#else
1632
#ifndef WOLFSSL_MLKEM_ENCAPSULATE_SMALL_MEM
1633
    sword16 y[((WC_ML_KEM_MAX_K + 3) * WC_ML_KEM_MAX_K + 3) * MLKEM_N];
1634
#else
1635
    sword16 y[(WC_ML_KEM_MAX_K + 2) * MLKEM_N];
1636
#ifndef WOLFSSL_MLKEM_NO_DECAPSULATE
1637
    byte block[MLKEM_MAX_COMP_POLY_SZ];
1638
#endif
1639
#endif
1640
#endif
1641
0
    sword16* u = 0;
1642
0
#ifndef WOLFSSL_MLKEM_ENCAPSULATE_SMALL_MEM
1643
0
    sword16* v = 0;
1644
#else
1645
    /* Matrix A from key generation, when it was kept. */
1646
#ifdef WOLFSSL_MLKEM_CACHE_A
1647
    const sword16* cachedA = ((key->flags & MLKEM_FLAG_A_SET) != 0) ?
1648
        key->a : NULL;
1649
    /* A decoded key has no cached matrix, so keep the one generated here. */
1650
    sword16* fillA = NULL;
1651
#else
1652
    const sword16* cachedA = NULL;
1653
    sword16* fillA = NULL;
1654
#endif
1655
#endif
1656
1657
    /* Establish parameters based on key type. */
1658
0
    switch (key->type) {
1659
0
#ifndef WOLFSSL_NO_ML_KEM
1660
0
#ifdef WOLFSSL_WC_ML_KEM_512
1661
0
    case WC_ML_KEM_512:
1662
0
        k = WC_ML_KEM_512_K;
1663
0
        compVecSz = WC_ML_KEM_512_POLY_VEC_COMPRESSED_SZ;
1664
0
        break;
1665
0
#endif
1666
0
#ifdef WOLFSSL_WC_ML_KEM_768
1667
0
    case WC_ML_KEM_768:
1668
0
        k = WC_ML_KEM_768_K;
1669
0
        compVecSz = WC_ML_KEM_768_POLY_VEC_COMPRESSED_SZ;
1670
0
        break;
1671
0
#endif
1672
0
#ifdef WOLFSSL_WC_ML_KEM_1024
1673
0
    case WC_ML_KEM_1024:
1674
0
        k = WC_ML_KEM_1024_K;
1675
0
        compVecSz = WC_ML_KEM_1024_POLY_VEC_COMPRESSED_SZ;
1676
0
        break;
1677
0
#endif
1678
0
#endif
1679
#ifdef WOLFSSL_MLKEM_KYBER
1680
#ifdef WOLFSSL_KYBER512
1681
    case KYBER512:
1682
        k = KYBER512_K;
1683
        compVecSz = KYBER512_POLY_VEC_COMPRESSED_SZ;
1684
        break;
1685
#endif
1686
#ifdef WOLFSSL_KYBER768
1687
    case KYBER768:
1688
        k = KYBER768_K;
1689
        compVecSz = KYBER768_POLY_VEC_COMPRESSED_SZ;
1690
        break;
1691
#endif
1692
#ifdef WOLFSSL_KYBER1024
1693
    case KYBER1024:
1694
        k = KYBER1024_K;
1695
        compVecSz = KYBER1024_POLY_VEC_COMPRESSED_SZ;
1696
        break;
1697
#endif
1698
#endif
1699
0
    default:
1700
        /* No other values supported. */
1701
0
        ret = NOT_COMPILED_IN;
1702
0
        break;
1703
0
    }
1704
0
#ifndef WOLFSSL_MLKEM_ENCAPSULATE_SMALL_MEM
1705
0
    if ((ret == 0) && (cmp != NULL)) {
1706
0
        ret = BAD_FUNC_ARG;
1707
0
    }
1708
0
#endif
1709
1710
0
#ifndef WOLFSSL_NO_MALLOC
1711
0
    if (ret == 0) {
1712
        /* Allocate dynamic memory for all matrices, vectors and polynomials. */
1713
0
#ifndef WOLFSSL_MLKEM_ENCAPSULATE_SMALL_MEM
1714
0
        yAllocSz = ((k + 3) * k + 3) * MLKEM_N * sizeof(sword16);
1715
#else
1716
        yAllocSz = (k + 2) * MLKEM_N * sizeof(sword16);
1717
        if (cmp != NULL) {
1718
            /* One block of cipher text to compare against. */
1719
            yAllocSz += MLKEM_MAX_COMP_POLY_SZ;
1720
        }
1721
#endif
1722
    #ifdef WC_MLKEM_NONBLOCK
1723
        if ((key->nb != NULL) && (key->nb->work != NULL)) {
1724
            /* Resume: reuse the working vectors from the previous call. */
1725
            y = (sword16*)key->nb->work;
1726
        }
1727
        else
1728
    #endif
1729
0
        {
1730
0
            y = (sword16*)XMALLOC(yAllocSz, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
1731
        #ifdef WC_MLKEM_NONBLOCK
1732
            if ((y != NULL) && (key->nb != NULL)) {
1733
                key->nb->work = y;
1734
                key->nb->workSz = (word32)yAllocSz;
1735
            }
1736
        #endif
1737
0
        }
1738
0
        if (y == NULL) {
1739
0
            ret = MEMORY_E;
1740
0
        }
1741
0
    }
1742
0
#endif
1743
1744
0
#ifndef WOLFSSL_MLKEM_ENCAPSULATE_SMALL_MEM
1745
0
    if (ret == 0) {
1746
        /* Assign allocated dynamic memory to pointers.
1747
         * y (b) | a (m) | mu (p) | e1 (p) | e2 (v) | u (v) | v (p) */
1748
0
        a  = y  + MLKEM_N * k;
1749
0
        mu = a  + MLKEM_N * k * k;
1750
0
        e1 = mu + MLKEM_N;
1751
0
        e2 = e1 + MLKEM_N * k;
1752
1753
        /* Convert msg to a polynomial.
1754
         * Step 20: mu <- Decompress_1(ByteDecode_1(m)) */
1755
0
        MLKEM_ARM64_SVR(ret = mlkem_from_msg(mu, m));
1756
0
    }
1757
0
    if (ret == 0) {
1758
        /* Initialize the PRF for use in the noise generation. */
1759
0
        ret = mlkem_prf_reset(&key->prf);
1760
0
    }
1761
0
    if (ret == 0) {
1762
        /* Generate noise using PRF.
1763
         * Steps 9-17: generate y, e_1, e_2
1764
         */
1765
0
        ret = mlkem_get_noise(&key->prf, (int)k, y, e1, e2, r);
1766
0
    }
1767
    #ifdef WOLFSSL_MLKEM_CACHE_A
1768
    if ((ret == 0) && ((key->flags & MLKEM_FLAG_A_SET) == 0)) {
1769
        sword16* fillA = key->a;
1770
1771
        if (fillA != NULL) {
1772
            ret = mlkem_gen_matrix(&key->prf, fillA, (int)k, key->pubSeed, 0);
1773
        }
1774
        if ((ret == 0) && (fillA != NULL)) {
1775
            key->flags |= MLKEM_FLAG_A_SET;
1776
        }
1777
    }
1778
    if ((ret == 0) && ((key->flags & MLKEM_FLAG_A_SET) != 0)) {
1779
        unsigned int i;
1780
        /* Transpose matrix.
1781
         *   Steps 4-8: generate matrix A_hat (from original) */
1782
        for (i = 0; i < k; i++) {
1783
            unsigned int j;
1784
            for (j = 0; j < k; j++) {
1785
                XMEMCPY(&a[(i * k + j) * MLKEM_N],
1786
                        &key->a[(j * k + i) * MLKEM_N],
1787
                        MLKEM_N * 2);
1788
            }
1789
        }
1790
    }
1791
    else
1792
    #endif /* WOLFSSL_MLKEM_CACHE_A */
1793
0
    if (ret == 0) {
1794
        /* Generate the transposed matrix.
1795
         *   Step 4-8: generate matrix A_hat */
1796
0
        ret = mlkem_gen_matrix(&key->prf, a, (int)k, key->pubSeed, 1);
1797
0
    }
1798
0
    if (ret == 0) {
1799
        /* Assign remaining allocated dynamic memory to pointers.
1800
         * y (b) | a (m) | mu (p) | e1 (p) | e2 (v) | u (v) | v (p) */
1801
0
        u  = e2 + MLKEM_N;
1802
0
        v  = u  + MLKEM_N * k;
1803
1804
        /* Perform encapsulation maths.
1805
         *   Steps 18-19, 21: calculate u and v */
1806
0
        ret = mlkem_encapsulate(key->pub, u, v, a, y, e1, e2, mu, (int)k);
1807
0
    }
1808
#else /* WOLFSSL_MLKEM_ENCAPSULATE_SMALL_MEM */
1809
    if (ret == 0) {
1810
        /* Assign allocated dynamic memory to pointers.
1811
         * y (v) | u (p) | a (p) [| block] */
1812
        u = y + MLKEM_N * k;
1813
        a = u + MLKEM_N;
1814
    }
1815
    /* Steps 9-12: generate y and transform it. Both run once; a non-blocking
1816
     * resume must not repeat them, as the NTT would be applied twice. */
1817
#ifdef WC_MLKEM_NONBLOCK
1818
    if ((ret == 0) && ((key->nb == NULL) || (key->nb->encState == 0)))
1819
#else
1820
    if (ret == 0)
1821
#endif
1822
    {
1823
        /* Initialize the PRF for use in the noise generation. */
1824
        ret = mlkem_prf_reset(&key->prf);
1825
        if (ret == 0) {
1826
            /* Generate noise using PRF.
1827
             * Steps 9-12: generate y */
1828
            ret = mlkem_get_noise(&key->prf, (int)k, y, NULL, NULL, r);
1829
        }
1830
        if (ret == 0) {
1831
            mlkem_encapsulate_ntt_y(y, (int)k);
1832
        }
1833
#ifdef WC_MLKEM_NONBLOCK
1834
        if ((ret == 0) && (key->nb != NULL)) {
1835
            key->nb->encState = 1;
1836
            key->nb->row = 0;
1837
            key->nb->cmpFail = 0;
1838
            ret = MP_WOULDBLOCK;
1839
        }
1840
#endif
1841
    }
1842
    if (ret == 0) {
1843
        byte* cb = c;
1844
        int cmpFail = 0;
1845
        int* cmpFailP = &cmpFail;
1846
        unsigned int i;
1847
        unsigned int i0 = 0;
1848
1849
        if (cmp != NULL) {
1850
            /* Cipher text is compared a block at a time as it is calculated. */
1851
#ifndef WOLFSSL_NO_MALLOC
1852
            cb = (byte*)(a + MLKEM_N);
1853
#elif !defined(WOLFSSL_MLKEM_NO_DECAPSULATE)
1854
            cb = block;
1855
#else
1856
            ret = BAD_FUNC_ARG;
1857
#endif
1858
        }
1859
#ifdef WOLFSSL_MLKEM_CACHE_A
1860
        if (cachedA == NULL) {
1861
            fillA = key->a;
1862
        }
1863
#endif
1864
#ifdef WC_MLKEM_NONBLOCK
1865
        if (key->nb != NULL) {
1866
            /* The row cursor and the compare result so far survive yields. */
1867
            i0 = key->nb->row;
1868
            cmpFailP = &key->nb->cmpFail;
1869
        }
1870
#endif
1871
1872
        /* Perform encapsulation maths and encode the cipher text.
1873
         *   Steps 13-16, 18-19, 22: one row of u per call when non-blocking */
1874
#ifdef WC_MLKEM_NONBLOCK
1875
        if ((key->nb == NULL) || (key->nb->encState == 1))
1876
#endif
1877
        {
1878
            for (i = i0; (ret == 0) && (i < k); i++) {
1879
                ret = mlkem_encapsulate_seeds_row(&key->prf, cb, cmp, cmpFailP,
1880
                    u, a, y, (int)k, key->pubSeed, r, cachedA, fillA, (int)i);
1881
#ifdef WC_MLKEM_NONBLOCK
1882
                /* Yield per row; the last row hands over to the v phase. */
1883
                if ((key->nb != NULL) && (ret == 0)) {
1884
                    key->nb->row = (word16)(i + 1);
1885
                    if (i + 1 == k) {
1886
                        key->nb->encState = 2;
1887
                    }
1888
                    ret = MP_WOULDBLOCK;
1889
                }
1890
#endif
1891
            }
1892
        }
1893
        /*   Steps 17, 20-21, 23-24: e_2, the message, v and c_2 */
1894
        if (ret == 0) {
1895
            ret = mlkem_encapsulate_seeds_tail(key->pub, &key->prf, cb, cmp,
1896
                fail, *cmpFailP, u, a, y, (int)k, m, r);
1897
        }
1898
#ifdef WOLFSSL_MLKEM_CACHE_A
1899
        if ((ret == 0) && (fillA != NULL)) {
1900
            key->flags |= MLKEM_FLAG_A_SET;
1901
        }
1902
#endif
1903
        ForceZero(&cmpFail, sizeof(cmpFail));
1904
    }
1905
    (void)compVecSz;
1906
#endif /* WOLFSSL_MLKEM_ENCAPSULATE_SMALL_MEM */
1907
1908
0
#ifndef WOLFSSL_MLKEM_ENCAPSULATE_SMALL_MEM
1909
0
    if (ret == 0) {
1910
0
        byte* c1 = c;
1911
0
        byte* c2 = c + compVecSz;
1912
1913
0
    #if defined(WOLFSSL_KYBER512) || defined(WOLFSSL_WC_ML_KEM_512)
1914
0
        if (k == WC_ML_KEM_512_K) {
1915
            /* Step 22: c_1 <- ByteEncode_d_u(Compress_d_u(u))
1916
             * Step 23: c_2 <- ByteEncode_d_v(Compress_d_v(v)) */
1917
0
            MLKEM_ARM64_SVR({
1918
0
                ret = mlkem_vec_compress_10(c1, u, k);
1919
0
                if (ret == 0)
1920
0
                    ret = mlkem_compress_4(c2, v);
1921
0
            });
1922
            /* Step 24: return c <- (c_1||c_2) */
1923
0
        }
1924
0
    #endif
1925
0
    #if defined(WOLFSSL_KYBER768) || defined(WOLFSSL_WC_ML_KEM_768)
1926
0
        if (k == WC_ML_KEM_768_K) {
1927
            /* Step 22: c_1 <- ByteEncode_d_u(Compress_d_u(u))
1928
             * Step 23: c_2 <- ByteEncode_d_v(Compress_d_v(v)) */
1929
0
            MLKEM_ARM64_SVR({
1930
0
                ret = mlkem_vec_compress_10(c1, u, k);
1931
0
                if (ret == 0)
1932
0
                    ret = mlkem_compress_4(c2, v);
1933
0
            });
1934
            /* Step 24: return c <- (c_1||c_2) */
1935
0
        }
1936
0
    #endif
1937
0
    #if defined(WOLFSSL_KYBER1024) || defined(WOLFSSL_WC_ML_KEM_1024)
1938
0
        if (k == WC_ML_KEM_1024_K) {
1939
            /* Step 22: c_1 <- ByteEncode_d_u(Compress_d_u(u))
1940
             * Step 23: c_2 <- ByteEncode_d_v(Compress_d_v(v)) */
1941
0
            MLKEM_ARM64_SVR({
1942
0
                ret = mlkem_vec_compress_11(c1, u, k);
1943
0
                if (ret == 0)
1944
0
                    ret = mlkem_compress_5(c2, v);
1945
0
            });
1946
            /* Step 24: return c <- (c_1||c_2) */
1947
0
        }
1948
0
    #endif
1949
0
    }
1950
0
    (void)fail;
1951
0
#endif /* !WOLFSSL_MLKEM_ENCAPSULATE_SMALL_MEM */
1952
1953
0
#ifndef WOLFSSL_NO_MALLOC
1954
    /* Dispose of dynamic memory allocated in function. The buffer holds secret
1955
     * material: y (ephemeral noise) and, in the default layout, mu (message
1956
     * polynomial) and e1/e2 (noise vectors). Zeroize the whole allocation
1957
     * before release - FIPS 203 section 3.3. */
1958
#ifdef WC_MLKEM_NONBLOCK
1959
    if ((key->nb != NULL) && (ret == WC_NO_ERR_TRACE(MP_WOULDBLOCK))) {
1960
        /* Yielding: keep the working vectors for the next call. */
1961
    }
1962
    else if (key->nb != NULL) {
1963
        /* Final success or error: release the working vectors, which the
1964
         * context owns even when this call failed before picking them up,
1965
         * and reset the cursor. The caller resets the rest. */
1966
        if (key->nb->work != NULL) {
1967
            ForceZero(key->nb->work, key->nb->workSz);
1968
            XFREE(key->nb->work, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
1969
        }
1970
        key->nb->work = NULL;
1971
        key->nb->workSz = 0;
1972
        key->nb->encState = 0;
1973
        key->nb->cmpFail = 0;
1974
        key->nb->row = 0;
1975
    }
1976
    else
1977
#endif
1978
0
    {
1979
0
        if (y != NULL) {
1980
0
            ForceZero(y, yAllocSz);
1981
0
            XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
1982
0
        }
1983
0
    }
1984
#else
1985
    /* y is a stack buffer holding secret noise/message material; zeroize it. */
1986
#ifdef WOLFSSL_CHECK_MEM_ZERO
1987
    wc_MemZero_Add("mlkem encrypt y", y, sizeof(y));
1988
#endif
1989
    ForceZero(y, sizeof(y));
1990
#ifdef WOLFSSL_CHECK_MEM_ZERO
1991
    wc_MemZero_Check(y, sizeof(y));
1992
#endif
1993
#if defined(WOLFSSL_MLKEM_ENCAPSULATE_SMALL_MEM) && \
1994
    !defined(WOLFSSL_MLKEM_NO_DECAPSULATE)
1995
    /* block holds cipher text re-encapsulated from the secret message. */
1996
    if (cmp != NULL) {
1997
    #ifdef WOLFSSL_CHECK_MEM_ZERO
1998
        wc_MemZero_Add("mlkem encrypt block", block, sizeof(block));
1999
    #endif
2000
        ForceZero(block, sizeof(block));
2001
    #ifdef WOLFSSL_CHECK_MEM_ZERO
2002
        wc_MemZero_Check(block, sizeof(block));
2003
    #endif
2004
    }
2005
#endif
2006
#endif
2007
2008
0
    return ret;
2009
0
}
2010
#endif /* !WOLF_CRYPTO_CB_ONLY_MLKEM */
2011
#endif
2012
2013
static int wc_mlkemkey_check_h(MlKemKey* key)
2014
0
{
2015
0
    int ret = 0;
2016
2017
    /* If public hash (h) is not stored against key, calculate it
2018
     * (fields set explicitly instead of using decode).
2019
     * Step 1: ... H(ek)...
2020
     */
2021
0
    if ((key->flags & MLKEM_FLAG_H_SET) == 0) {
2022
0
    #ifndef WOLFSSL_NO_MALLOC
2023
0
        byte* pubKey = NULL;
2024
0
        word32 pubKeyLen;
2025
    #else
2026
        byte pubKey[WC_ML_KEM_MAX_PUBLIC_KEY_SIZE];
2027
        word32 pubKeyLen;
2028
    #endif
2029
2030
        /* Determine how big an encoded public key will be. */
2031
0
        ret = wc_MlKemKey_PublicKeySize(key, &pubKeyLen);
2032
0
        if (ret == 0) {
2033
0
    #ifndef WOLFSSL_NO_MALLOC
2034
            /* Allocate dynamic memory for encoded public key. */
2035
0
            pubKey = (byte*)XMALLOC(pubKeyLen, key->heap,
2036
0
                DYNAMIC_TYPE_TMP_BUFFER);
2037
0
            if (pubKey == NULL) {
2038
0
                ret = MEMORY_E;
2039
0
            }
2040
0
        }
2041
0
        if (ret == 0) {
2042
0
    #endif
2043
            /* Encode public key - h is hash of encoded public key. */
2044
0
            ret = wc_MlKemKey_EncodePublicKey(key, pubKey, pubKeyLen);
2045
0
        }
2046
0
    #ifndef WOLFSSL_NO_MALLOC
2047
        /* Dispose of encoded public key. */
2048
0
        XFREE(pubKey, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
2049
0
    #endif
2050
0
    }
2051
2052
0
    return ret;
2053
0
}
2054
2055
#ifndef WOLFSSL_MLKEM_NO_ENCAPSULATE
2056
/**
2057
 * Encapsulate with random number generator and derive secret.
2058
 *
2059
 * FIPS 203, Algorithm 20: ML-KEM.Encaps(ek)
2060
 * Uses the encapsulation key to generate a shared secret key and an associated
2061
 * ciphertext.
2062
 *   1: m <- B_32                                         > m is 32 random bytes
2063
 *   2: if m == NULL then
2064
 *   3:     return falsum
2065
 *   4: end if
2066
 *   5: (K,c) <- ML-KEM.Encaps_internal(ek,m)
2067
 *                                        > run internal encapsulation algorithm
2068
 *   6: return (K,c)
2069
 *
2070
 * @param  [in]   key  ML-KEM key object.
2071
 * @param  [out]  ct   Cipher text.
2072
 * @param  [out]  ss   Shared secret generated.
2073
 * @param  [in]   rng  Random number generator.
2074
 * @return  0 on success.
2075
 * @return  BAD_FUNC_ARG when key, ct, ss or rng is NULL.
2076
 * @return  BAD_STATE_E when public key not set.
2077
 * @return  NOT_COMPILED_IN when key type is not supported.
2078
 * @return  MEMORY_E when dynamic memory allocation failed.
2079
 */
2080
int wc_MlKemKey_Encapsulate(MlKemKey* key, unsigned char* ct, unsigned char* ss,
2081
    WC_RNG* rng)
2082
0
{
2083
0
#ifndef WC_NO_RNG
2084
0
    int ret = 0;
2085
0
    unsigned char m[WC_ML_KEM_ENC_RAND_SZ];
2086
#ifdef WOLF_CRYPTO_CB
2087
    word32 ctlen = 0;
2088
#endif
2089
2090
    /* Validate parameters. */
2091
0
    if ((key == NULL) || (ct == NULL) || (ss == NULL) || (rng == NULL)) {
2092
0
        ret = BAD_FUNC_ARG;
2093
0
    }
2094
0
    else if (((key->flags & MLKEM_FLAG_PUB_SET) == 0) &&
2095
0
             !MLKEM_KEY_ON_DEVICE(key)) {
2096
0
        ret = BAD_STATE_E;
2097
0
    }
2098
2099
#ifdef WOLF_CRYPTO_CB
2100
    if (ret == 0) {
2101
        ret = wc_MlKemKey_CipherTextSize(key, &ctlen);
2102
    }
2103
#ifndef WOLF_CRYPTO_CB_FIND
2104
    if ((ret == 0) && (key->devId != INVALID_DEVID)) {
2105
#else
2106
    if (ret == 0) {
2107
#endif
2108
        ret = wc_CryptoCb_PqcEncapsulate(ct, ctlen, ss, WC_ML_KEM_SS_SZ, rng,
2109
            WC_PQC_KEM_TYPE_MLKEM, key);
2110
        if (ret == WC_NO_ERR_TRACE(WC_PENDING_E))
2111
            ret = BAD_STATE_E; /* async unsupported for KEM encaps */
2112
        if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE))
2113
            return ret;
2114
        /* fall-through when unavailable */
2115
        ret = 0;
2116
    }
2117
#endif
2118
    /* Only software needs a local public key. */
2119
0
    if ((ret == 0) && ((key->flags & MLKEM_FLAG_PUB_SET) == 0)) {
2120
0
        ret = BAD_STATE_E;
2121
0
    }
2122
2123
0
    if (ret == 0) {
2124
#ifdef WC_MLKEM_NONBLOCK
2125
        if ((key->nb != NULL) && (key->nb->op == MLKEM_NB_OP_ENCAP) &&
2126
                (key->nb->arg == ct) && key->nb->fromRng) {
2127
            /* Resume: reuse the randomness drawn on the first call so each
2128
             * resumed phase produces the same ciphertext and secret. Only an
2129
             * encapsulation started here: one started with a caller's m is
2130
             * not this operation. */
2131
            XMEMCPY(m, key->nb->rand, sizeof(m));
2132
        }
2133
        else
2134
#endif
2135
0
        {
2136
        /* Generate seed for use with PRFs.
2137
         * Step 1: m is 32 random bytes
2138
         */
2139
0
        ret = wc_RNG_GenerateBlock(rng, m, sizeof(m));
2140
0
        }
2141
        /* m now holds the encapsulation randomness (the shared secret is
2142
         * derived from it); register before the encapsulate call. */
2143
#ifdef WOLFSSL_CHECK_MEM_ZERO
2144
        wc_MemZero_Add("mlkem encapsulate m", m, sizeof(m));
2145
#endif
2146
        /* Step 2: ret is not zero when m == NULL. */
2147
0
    }
2148
0
    if (ret == 0) {
2149
        /* Encapsulate with the random.
2150
         * Step 5: run internal encapsulation algorithm
2151
         */
2152
0
        ret = wc_MlKemKey_EncapsulateWithRandom(key, ct, ss, m, sizeof(m));
2153
#ifdef WC_MLKEM_NONBLOCK
2154
        if ((key->nb != NULL) && (ret == WC_NO_ERR_TRACE(MP_WOULDBLOCK))) {
2155
            key->nb->fromRng = 1;
2156
        }
2157
#endif
2158
0
    }
2159
2160
    /* Zeroize the random message seed before return - it is the encapsulation
2161
     * randomness from which the shared secret is derived (FIPS 203 Alg 17). */
2162
0
    ForceZero(m, sizeof(m));
2163
#ifdef WOLFSSL_CHECK_MEM_ZERO
2164
    wc_MemZero_Check(m, sizeof(m));
2165
#endif
2166
2167
    /* Step 3: return ret != 0 on falsum or internal key generation failure. */
2168
0
    return ret;
2169
#else
2170
    (void)key;
2171
    (void)ct;
2172
    (void)ss;
2173
    (void)rng;
2174
    return NOT_COMPILED_IN;
2175
#endif /* WC_NO_RNG */
2176
0
}
2177
2178
/**
2179
 * Encapsulate with random data and derive secret.
2180
 *
2181
 * FIPS 203, Algorithm 17: ML-KEM.Encaps_internal(ek, m)
2182
 * Uses the encapsulation key and randomness to generate a key and an associated
2183
 * ciphertext.
2184
 *   Step 1: (K,r) <- G(m||H(ek))
2185
 *                                 > derive shared secret key K and randomness r
2186
 *   Step 2: c <- K-PKE.Encrypt(ek, m, r)
2187
 *                                     > encrypt m using K-PKE with randomness r
2188
 *   Step 3: return (K,c)
2189
 *
2190
 * @param  [in]   key   ML-KEM key object.
2191
 * @param  [out]  ct    Cipher text.
2192
 * @param  [out]  ss    Shared secret generated.
2193
 * @param  [in]   rand  Random bytes.
2194
 * @param  [in]   len   Length of random bytes.
2195
 * @return  0 on success.
2196
 * @return  BAD_FUNC_ARG when key, ct, ss or rand is NULL.
2197
 * @return  BUFFER_E when len is not WC_ML_KEM_ENC_RAND_SZ.
2198
 * @return  BAD_STATE_E when public key not set.
2199
 * @return  NOT_COMPILED_IN when key type is not supported.
2200
 * @return  MEMORY_E when dynamic memory allocation failed.
2201
 */
2202
int wc_MlKemKey_EncapsulateWithRandom(MlKemKey* key, unsigned char* ct,
2203
    unsigned char* ss, const unsigned char* rand, int len)
2204
0
{
2205
#ifdef WOLF_CRYPTO_CB_ONLY_MLKEM
2206
    /* Validate as the software path does, so the reported error stays the
2207
     * same for a bad call. */
2208
    if ((key == NULL) || (ct == NULL) || (ss == NULL) || (rand == NULL)) {
2209
        return BAD_FUNC_ARG;
2210
    }
2211
    if (len != WC_ML_KEM_ENC_RAND_SZ) {
2212
        return BUFFER_E;
2213
    }
2214
    if ((key->flags & MLKEM_FLAG_PUB_SET) == 0) {
2215
        return BAD_STATE_E;
2216
    }
2217
    return NO_VALID_DEVID;
2218
#else
2219
#ifdef WOLFSSL_MLKEM_KYBER
2220
    byte msg[WC_ML_KEM_SYM_SZ];
2221
#endif
2222
0
    byte kr[2 * WC_ML_KEM_SYM_SZ + 1];
2223
0
    int ret = 0;
2224
0
    word32 ctSz = 0;
2225
#ifdef WOLFSSL_MLKEM_KYBER
2226
    unsigned int cSz = 0;
2227
#endif
2228
2229
    /* msg (Kyber only) and kr hold secret encapsulation material; baseline-zero
2230
     * and register up front (single-exit function) so any later exit before the
2231
     * ForceZero is covered. */
2232
#if defined(WOLFSSL_MLKEM_KYBER) && defined(WOLFSSL_CHECK_MEM_ZERO)
2233
    XMEMSET(msg, 0, sizeof(msg));
2234
    wc_MemZero_Add("mlkem encapsulate msg", msg, sizeof(msg));
2235
#endif
2236
#ifdef WOLFSSL_CHECK_MEM_ZERO
2237
    XMEMSET(kr, 0, sizeof(kr));
2238
    wc_MemZero_Add("mlkem encapsulate kr", kr, sizeof(kr));
2239
    if (key != NULL) {
2240
        mlkemkey_hash_memzero_add(key);
2241
    }
2242
#endif
2243
    /* Validate parameters. */
2244
0
    if ((key == NULL) || (ct == NULL) || (ss == NULL) || (rand == NULL)) {
2245
0
        ret = BAD_FUNC_ARG;
2246
0
    }
2247
0
    if ((ret == 0) && (len != WC_ML_KEM_ENC_RAND_SZ)) {
2248
0
        ret = BUFFER_E;
2249
0
    }
2250
#ifdef WC_MLKEM_NONBLOCK
2251
    if (ret == 0) {
2252
        /* Resume only the encapsulation of this m into this buffer. */
2253
        if (mlkemkey_nb_begin(key, MLKEM_NB_OP_ENCAP, rand,
2254
                WC_ML_KEM_ENC_RAND_SZ, ct) == 1) {
2255
            WOLFSSL_MSG("ML-KEM non-blocking encapsulate starting");
2256
        } else {
2257
            WOLFSSL_MSG("ML-KEM non-blocking encapsulate resuming or unset");
2258
        }
2259
    }
2260
#endif
2261
    /* Check the public key has been set. */
2262
0
    if ((ret == 0) && ((key->flags & MLKEM_FLAG_PUB_SET) == 0)) {
2263
0
        ret = BAD_STATE_E;
2264
0
    }
2265
2266
#ifdef WOLFSSL_MLKEM_KYBER
2267
    if (ret == 0) {
2268
        /* Establish parameters based on key type. */
2269
        switch (key->type) {
2270
#ifndef WOLFSSL_NO_ML_KEM
2271
    #ifdef WOLFSSL_WC_ML_KEM_512
2272
        case WC_ML_KEM_512:
2273
    #endif
2274
    #ifdef WOLFSSL_WC_ML_KEM_768
2275
        case WC_ML_KEM_768:
2276
    #endif
2277
    #ifdef WOLFSSL_WC_ML_KEM_1024
2278
        case WC_ML_KEM_1024:
2279
    #endif
2280
            break;
2281
#endif
2282
    #ifdef WOLFSSL_KYBER512
2283
        case KYBER512:
2284
            cSz = KYBER512_CIPHER_TEXT_SIZE;
2285
            break;
2286
    #endif
2287
    #ifdef WOLFSSL_KYBER768
2288
        case KYBER768:
2289
            cSz = KYBER768_CIPHER_TEXT_SIZE;
2290
            break;
2291
    #endif
2292
    #ifdef WOLFSSL_KYBER1024
2293
        case KYBER1024:
2294
            cSz = KYBER1024_CIPHER_TEXT_SIZE;
2295
            break;
2296
    #endif
2297
        default:
2298
            /* No other values supported. */
2299
            ret = NOT_COMPILED_IN;
2300
            break;
2301
        }
2302
    }
2303
#endif
2304
2305
0
    if (ret == 0) {
2306
0
        ret = wc_mlkemkey_check_h(key);
2307
0
    }
2308
2309
#ifdef WOLFSSL_MLKEM_KYBER
2310
    if (ret == 0) {
2311
#ifndef WOLFSSL_NO_ML_KEM
2312
        if (key->type & MLKEM_KYBER)
2313
#endif
2314
        {
2315
            /* Hash random to anonymize as seed data. */
2316
            ret = MLKEM_HASH_H(&key->hash, rand, WC_ML_KEM_SYM_SZ, msg);
2317
        }
2318
    }
2319
#endif
2320
0
    if (ret == 0) {
2321
        /* Hash message into seed buffer. */
2322
#if defined(WOLFSSL_MLKEM_KYBER) && !defined(WOLFSSL_NO_ML_KEM)
2323
        if (key->type & MLKEM_KYBER)
2324
#endif
2325
#ifdef WOLFSSL_MLKEM_KYBER
2326
        {
2327
            ret = MLKEM_HASH_G(&key->hash, msg, WC_ML_KEM_SYM_SZ, key->h,
2328
                WC_ML_KEM_SYM_SZ, kr);
2329
        }
2330
#endif
2331
#if defined(WOLFSSL_MLKEM_KYBER) && !defined(WOLFSSL_NO_ML_KEM)
2332
        else
2333
#endif
2334
0
#ifndef WOLFSSL_NO_ML_KEM
2335
0
        {
2336
            /* Step 1: (K,r) <- G(m||H(ek)) */
2337
0
            ret = MLKEM_HASH_G(&key->hash, rand, WC_ML_KEM_SYM_SZ, key->h,
2338
0
                WC_ML_KEM_SYM_SZ, kr);
2339
0
        }
2340
0
#endif
2341
0
    }
2342
2343
0
    if (ret == 0) {
2344
        /* Encapsulate the message using the key and the seed. */
2345
#if defined(WOLFSSL_MLKEM_KYBER) && !defined(WOLFSSL_NO_ML_KEM)
2346
        if (key->type & MLKEM_KYBER)
2347
#endif
2348
#ifdef WOLFSSL_MLKEM_KYBER
2349
        {
2350
            ret = mlkemkey_encapsulate(key, msg, kr + WC_ML_KEM_SYM_SZ, ct,
2351
                NULL, NULL);
2352
        }
2353
#endif
2354
#if defined(WOLFSSL_MLKEM_KYBER) && !defined(WOLFSSL_NO_ML_KEM)
2355
        else
2356
#endif
2357
0
#ifndef WOLFSSL_NO_ML_KEM
2358
0
        {
2359
            /* Step 2: c <- K-PKE.Encrypt(ek,m,r) */
2360
0
            ret = mlkemkey_encapsulate(key, rand, kr + WC_ML_KEM_SYM_SZ, ct,
2361
0
                NULL, NULL);
2362
0
        }
2363
0
#endif
2364
0
    }
2365
2366
#if defined(WOLFSSL_MLKEM_KYBER) && !defined(WOLFSSL_NO_ML_KEM)
2367
    /* key may be NULL here; reading it lets the compiler drop later checks. */
2368
    if ((ret == 0) && (key->type & MLKEM_KYBER))
2369
#endif
2370
#ifdef WOLFSSL_MLKEM_KYBER
2371
    {
2372
        if (ret == 0) {
2373
            /* Hash the cipher text after the seed. */
2374
            ret = MLKEM_HASH_H(&key->hash, ct, cSz, kr + WC_ML_KEM_SYM_SZ);
2375
        }
2376
        if (ret == 0) {
2377
            /* Derive the secret from the seed and hash of cipher text. */
2378
            ret = MLKEM_KDF(kr, 2 * WC_ML_KEM_SYM_SZ, ss, WC_ML_KEM_SS_SZ);
2379
        }
2380
    }
2381
#endif
2382
#if defined(WOLFSSL_MLKEM_KYBER) && !defined(WOLFSSL_NO_ML_KEM)
2383
    else
2384
#endif
2385
0
#ifndef WOLFSSL_NO_ML_KEM
2386
0
    {
2387
0
        if (ret == 0) {
2388
            /* return (K,c) */
2389
0
            XMEMCPY(ss, kr, WC_ML_KEM_SS_SZ);
2390
0
        }
2391
0
    }
2392
0
#endif
2393
2394
0
    if ((ret != 0) &&
2395
#ifdef WC_MLKEM_NONBLOCK
2396
            (ret != WC_NO_ERR_TRACE(MP_WOULDBLOCK)) &&
2397
#endif
2398
0
            (ct != NULL) && (wc_MlKemKey_CipherTextSize(key, &ctSz) == 0)) {
2399
        /* FIPS 203 3.3: a failed encapsulation leaves no ciphertext. */
2400
0
        ForceZero(ct, ctSz);
2401
0
    }
2402
#ifdef WC_MLKEM_NONBLOCK
2403
    if ((key != NULL) && (ret != WC_NO_ERR_TRACE(MP_WOULDBLOCK))) {
2404
        /* Final success or error: reset the context. */
2405
        mlkemkey_nb_release(key);
2406
    }
2407
#endif
2408
0
    if (key != NULL) {
2409
0
        mlkemkey_hash_wipe(&key->hash);
2410
0
        mlkemkey_hash_wipe(&key->prf);
2411
    #ifdef WOLFSSL_CHECK_MEM_ZERO
2412
        mlkemkey_hash_memzero_check(key);
2413
    #endif
2414
0
    }
2415
2416
#ifdef WOLFSSL_MLKEM_KYBER
2417
    /* msg holds the secret message H(rand) used for Kyber encapsulation;
2418
     * zeroize it before return (the ML-KEM path uses the caller's rand). */
2419
    ForceZero(msg, sizeof(msg));
2420
#ifdef WOLFSSL_CHECK_MEM_ZERO
2421
    wc_MemZero_Check(msg, sizeof(msg));
2422
#endif
2423
#endif
2424
0
    ForceZero(kr, sizeof(kr));
2425
#ifdef WOLFSSL_CHECK_MEM_ZERO
2426
    wc_MemZero_Check(kr, sizeof(kr));
2427
#endif
2428
2429
0
    return ret;
2430
0
#endif /* WOLF_CRYPTO_CB_ONLY_MLKEM */
2431
0
}
2432
#endif /* !WOLFSSL_MLKEM_NO_ENCAPSULATE */
2433
2434
/******************************************************************************/
2435
2436
#ifndef WOLFSSL_MLKEM_NO_DECAPSULATE
2437
#ifndef WOLF_CRYPTO_CB_ONLY_MLKEM
2438
/* Decapsulate cipher text to the message using key.
2439
 *
2440
 * FIPS 203, Algorithm 15: K-PKE.Decrypt(dk_PKE,c)
2441
 * Uses the decryption key to decrypt a ciphertext.
2442
 *   1: c1 <- c[0 : 32.d_u.k]
2443
 *   2: c2 <- c[32.d_u.k : 32(d_u.k + d_v)]
2444
 *   3: u' <- Decompress_d_u(ByteDecode_d_u(c1))
2445
 *   4: v' <- Decompress_d_v(ByteDecode_d_v(c2))
2446
 *   ...
2447
 *   6: w <- v' - InvNTT(s_hat_trans o NTT(u'))
2448
 *   7: m <- ByteEncode_1(Compress_1(w))
2449
 *   8: return m
2450
 *
2451
 * @param  [in]   key  ML-KEM key object.
2452
 * @param  [out]  m    Message that was encapsulated.
2453
 * @param  [in]   c    Cipher text.
2454
 * @return  0 on success.
2455
 * @return  NOT_COMPILED_IN when key type is not supported.
2456
 * @return  MEMORY_E when dynamic memory allocation failed.
2457
 */
2458
static MLKEM_NOINLINE int mlkemkey_decapsulate(MlKemKey* key, byte* m,
2459
    const byte* c)
2460
0
{
2461
0
    int ret = 0;
2462
0
    sword16* v;
2463
0
    sword16* w = NULL;
2464
0
    unsigned int k = 0;
2465
0
    unsigned int compVecSz = 0;
2466
0
#if defined(WOLFSSL_SMALL_STACK) || \
2467
0
    (!defined(USE_INTEL_SPEEDUP) && !defined(WOLFSSL_NO_MALLOC))
2468
0
    sword16* u = NULL;
2469
0
    size_t uAllocSz = 0;
2470
#else
2471
    sword16 u[(WC_ML_KEM_MAX_K + 1) * MLKEM_N];
2472
#endif
2473
2474
    /* Establish parameters based on key type. */
2475
0
    switch (key->type) {
2476
0
#ifndef WOLFSSL_NO_ML_KEM
2477
0
#ifdef WOLFSSL_WC_ML_KEM_512
2478
0
    case WC_ML_KEM_512:
2479
0
        k = WC_ML_KEM_512_K;
2480
0
        compVecSz = WC_ML_KEM_512_POLY_VEC_COMPRESSED_SZ;
2481
0
        break;
2482
0
#endif
2483
0
#ifdef WOLFSSL_WC_ML_KEM_768
2484
0
    case WC_ML_KEM_768:
2485
0
        k = WC_ML_KEM_768_K;
2486
0
        compVecSz = WC_ML_KEM_768_POLY_VEC_COMPRESSED_SZ;
2487
0
        break;
2488
0
#endif
2489
0
#ifdef WOLFSSL_WC_ML_KEM_1024
2490
0
    case WC_ML_KEM_1024:
2491
0
        k = WC_ML_KEM_1024_K;
2492
0
        compVecSz = WC_ML_KEM_1024_POLY_VEC_COMPRESSED_SZ;
2493
0
        break;
2494
0
#endif
2495
0
#endif
2496
#ifdef WOLFSSL_MLKEM_KYBER
2497
#ifdef WOLFSSL_KYBER512
2498
    case KYBER512:
2499
        k = KYBER512_K;
2500
        compVecSz = KYBER512_POLY_VEC_COMPRESSED_SZ;
2501
        break;
2502
#endif
2503
#ifdef WOLFSSL_KYBER768
2504
    case KYBER768:
2505
        k = KYBER768_K;
2506
        compVecSz = KYBER768_POLY_VEC_COMPRESSED_SZ;
2507
        break;
2508
#endif
2509
#ifdef WOLFSSL_KYBER1024
2510
    case KYBER1024:
2511
        k = KYBER1024_K;
2512
        compVecSz = KYBER1024_POLY_VEC_COMPRESSED_SZ;
2513
        break;
2514
#endif
2515
#endif
2516
0
    default:
2517
        /* No other values supported. */
2518
0
        ret = NOT_COMPILED_IN;
2519
0
        break;
2520
0
    }
2521
2522
0
#if defined(WOLFSSL_SMALL_STACK) || \
2523
0
    (!defined(USE_INTEL_SPEEDUP) && !defined(WOLFSSL_NO_MALLOC))
2524
0
    if (ret == 0) {
2525
        /* Allocate dynamic memory for a vector and a polynomial. */
2526
0
        uAllocSz = (k + 1) * MLKEM_N * sizeof(sword16);
2527
0
        u = (sword16*)XMALLOC(uAllocSz, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
2528
0
        if (u == NULL) {
2529
0
            ret = MEMORY_E;
2530
0
        }
2531
0
    }
2532
0
#endif
2533
0
    if (ret == 0) {
2534
        /* Step 1: c1 <- c[0 : 32.d_u.k] */
2535
0
        const byte* c1 = c;
2536
        /* Step 2: c2 <- c[32.d_u.k : 32(d_u.k + d_v)] */
2537
0
        const byte* c2 = c + compVecSz;
2538
2539
        /* Assign allocated dynamic memory to pointers.
2540
         * u (v) | v (p) */
2541
0
        v = u + k * MLKEM_N;
2542
0
        w = u;
2543
2544
0
    #if defined(WOLFSSL_KYBER512) || defined(WOLFSSL_WC_ML_KEM_512)
2545
0
        if (k == WC_ML_KEM_512_K) {
2546
            /* Step 3: u' <- Decompress_d_u(ByteDecode_d_u(c1)) */
2547
0
            if (ret == 0) {
2548
0
                ret = mlkem_vec_decompress_10(u, c1, k);
2549
0
            }
2550
            /* Step 4: v' <- Decompress_d_v(ByteDecode_d_v(c2)) */
2551
0
            if (ret == 0) {
2552
0
                ret = mlkem_decompress_4(v, c2);
2553
0
            }
2554
0
        }
2555
0
    #endif
2556
0
    #if defined(WOLFSSL_KYBER768) || defined(WOLFSSL_WC_ML_KEM_768)
2557
0
        if (k == WC_ML_KEM_768_K) {
2558
            /* Step 3: u' <- Decompress_d_u(ByteDecode_d_u(c1)) */
2559
0
            if (ret == 0) {
2560
0
                ret = mlkem_vec_decompress_10(u, c1, k);
2561
0
            }
2562
            /* Step 4: v' <- Decompress_d_v(ByteDecode_d_v(c2)) */
2563
0
            if (ret == 0) {
2564
0
                ret = mlkem_decompress_4(v, c2);
2565
0
            }
2566
0
        }
2567
0
    #endif
2568
0
    #if defined(WOLFSSL_KYBER1024) || defined(WOLFSSL_WC_ML_KEM_1024)
2569
0
        if (k == WC_ML_KEM_1024_K) {
2570
            /* Step 3: u' <- Decompress_d_u(ByteDecode_d_u(c1)) */
2571
0
            if (ret == 0) {
2572
0
                ret = mlkem_vec_decompress_11(u, c1);
2573
0
            }
2574
            /* Step 4: v' <- Decompress_d_v(ByteDecode_d_v(c2)) */
2575
0
            if (ret == 0) {
2576
0
                ret = mlkem_decompress_5(v, c2);
2577
0
            }
2578
0
        }
2579
0
    #endif
2580
2581
        /* Decapsulate the cipher text into polynomial.
2582
         * Step 6: w <- v' - InvNTT(s_hat_trans o NTT(u')) */
2583
0
        if (ret == 0) {
2584
0
            ret = mlkem_decapsulate(key->priv, w, u, v, (int)k);
2585
0
        }
2586
0
    }
2587
0
    if (ret == 0) {
2588
2589
        /* Convert the polynomial into a array of bytes (message).
2590
         * Step 7: m <- ByteEncode_1(Compress_1(w)) */
2591
0
        MLKEM_ARM64_SVR(ret = mlkem_to_msg(m, w));
2592
        /* Step 8: return m */
2593
0
    }
2594
2595
0
#if defined(WOLFSSL_SMALL_STACK) || \
2596
0
    (!defined(USE_INTEL_SPEEDUP) && !defined(WOLFSSL_NO_MALLOC))
2597
    /* Dispose of dynamic memory allocated in function. u (aliased as w) holds
2598
     * the secret decrypted polynomial w = v' - InvNTT(s_hat^T o NTT(u')) from
2599
     * K-PKE.Decrypt; zeroize the whole buffer before release - FIPS 203
2600
     * section 3.3. */
2601
0
    if (u != NULL) {
2602
0
        ForceZero(u, uAllocSz);
2603
0
        XFREE(u, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
2604
0
    }
2605
#else
2606
    /* u is a stack buffer holding the secret decrypted polynomial; zeroize. */
2607
#ifdef WOLFSSL_CHECK_MEM_ZERO
2608
    wc_MemZero_Add("mlkem decrypt u", u, sizeof(u));
2609
#endif
2610
    ForceZero(u, sizeof(u));
2611
#ifdef WOLFSSL_CHECK_MEM_ZERO
2612
    wc_MemZero_Check(u, sizeof(u));
2613
#endif
2614
#endif
2615
2616
0
    return ret;
2617
0
}
2618
#endif /* !WOLF_CRYPTO_CB_ONLY_MLKEM */
2619
2620
/**
2621
 * Decapsulate the cipher text to calculate the shared secret.
2622
 *
2623
 * Validates the cipher text by encapsulating and comparing with data passed in.
2624
 *
2625
 * FIPS 203, Algorithm 21: ML-KEM.Decaps(dk, c)
2626
 * Uses the decapsulation key to produce a shared secret key from a ciphertext.
2627
 *   1: K' <- ML-KEM.Decaps_internal(dk,c)
2628
 *                                        > run internal decapsulation algorithm
2629
 *   2: return K'
2630
 *
2631
 * FIPS 203, Algorithm 18: ML-KEM.Decaps_internal(dk, c)
2632
 * Uses the decapsulation key to produce a shared secret key from a ciphertext.
2633
 *   ...
2634
 *   1: dk_PKE <- dk[0 : 384k]
2635
 *                        > extract (from KEM decaps key) the PKE decryption key
2636
 *   2: ek_PKE <- dk[384k : 768k + 32]
2637
 *                                                  > extract PKE encryption key
2638
 *   3: h <- dk[768k + 32 : 768k + 64]
2639
 *                                          > extract hash of PKE encryption key
2640
 *   4: z <- dk[768k + 64 : 768k + 96]
2641
 *                                            > extract implicit rejection value
2642
 *   5: m' <- K-PKE.Decrypt(dk_PKE, c)                      > decrypt ciphertext
2643
 *   6: (K', r') <- G(m'||h)
2644
 *   7: K_bar <- J(z||c)
2645
 *   8: c' <- K-PKE.Encrypt(ek_PKE, m', r')
2646
 *                                  > re-encrypt using the derived randomness r'
2647
 *   9: if c != c' then
2648
 *  10:      K' <- K_bar
2649
 *                            > if ciphertexts do not match, "implicitly reject"
2650
 *  11: end if
2651
 *  12: return K'
2652
 *
2653
 * @param  [in]   key  ML-KEM key object.
2654
 * @param  [out]  ss   Shared secret.
2655
 * @param  [in]   ct   Cipher text.
2656
 * @param  [in]   len  Length of cipher text.
2657
 * @return  0 on success.
2658
 * @return  BAD_FUNC_ARG when key, ss or ct are NULL.
2659
 * @return  BAD_STATE_E when private key is not set.
2660
 * @return  NOT_COMPILED_IN when key type is not supported.
2661
 * @return  BUFFER_E when len is not the length of cipher text for the key type.
2662
 * @return  MEMORY_E when dynamic memory allocation failed.
2663
 */
2664
int wc_MlKemKey_Decapsulate(MlKemKey* key, unsigned char* ss,
2665
    const unsigned char* ct, word32 len)
2666
0
{
2667
0
    int ret = 0;
2668
0
    unsigned int ctSz = 0;
2669
0
#ifndef WOLF_CRYPTO_CB_ONLY_MLKEM
2670
0
    byte msg[WC_ML_KEM_SYM_SZ];
2671
0
    byte kr[2 * WC_ML_KEM_SYM_SZ + 1];
2672
0
    unsigned int i = 0;
2673
0
    int fail = -1; /* mismatch until mlkem_cmp() says otherwise */
2674
0
#ifndef WOLFSSL_MLKEM_ENCAPSULATE_SMALL_MEM
2675
0
#if defined(WOLFSSL_SMALL_STACK) || \
2676
0
    (!defined(USE_INTEL_SPEEDUP) && !defined(WOLFSSL_NO_MALLOC))
2677
0
    byte* cmp = NULL;
2678
#else
2679
    byte cmp[WC_ML_KEM_MAX_CIPHER_TEXT_SIZE];
2680
#endif
2681
0
#endif
2682
0
#endif
2683
2684
    /* Validate parameters. */
2685
0
    if ((key == NULL) || (ss == NULL) || (ct == NULL)) {
2686
0
        ret = BAD_FUNC_ARG;
2687
0
    }
2688
0
    if (ret == 0) {
2689
        /* Establish cipher text size based on key type. */
2690
0
        switch (key->type) {
2691
0
#ifndef WOLFSSL_NO_ML_KEM
2692
0
    #ifdef WOLFSSL_WC_ML_KEM_512
2693
0
        case WC_ML_KEM_512:
2694
0
            ctSz = WC_ML_KEM_512_CIPHER_TEXT_SIZE;
2695
0
            break;
2696
0
    #endif
2697
0
    #ifdef WOLFSSL_WC_ML_KEM_768
2698
0
        case WC_ML_KEM_768:
2699
0
            ctSz = WC_ML_KEM_768_CIPHER_TEXT_SIZE;
2700
0
            break;
2701
0
    #endif
2702
0
    #ifdef WOLFSSL_WC_ML_KEM_1024
2703
0
        case WC_ML_KEM_1024:
2704
0
            ctSz = WC_ML_KEM_1024_CIPHER_TEXT_SIZE;
2705
0
            break;
2706
0
    #endif
2707
0
#endif
2708
#ifdef WOLFSSL_MLKEM_KYBER
2709
    #ifdef WOLFSSL_KYBER512
2710
        case KYBER512:
2711
            ctSz = KYBER512_CIPHER_TEXT_SIZE;
2712
            break;
2713
    #endif
2714
    #ifdef WOLFSSL_KYBER768
2715
        case KYBER768:
2716
            ctSz = KYBER768_CIPHER_TEXT_SIZE;
2717
            break;
2718
    #endif
2719
    #ifdef WOLFSSL_KYBER1024
2720
        case KYBER1024:
2721
            ctSz = KYBER1024_CIPHER_TEXT_SIZE;
2722
            break;
2723
    #endif
2724
#endif
2725
0
        default:
2726
            /* No other values supported. */
2727
0
            ret = NOT_COMPILED_IN;
2728
0
            break;
2729
0
        }
2730
0
    }
2731
2732
    /* Ensure the cipher text passed in is the correct size. */
2733
0
    if ((ret == 0) && (len != ctSz)) {
2734
0
        ret = BUFFER_E;
2735
0
    }
2736
2737
#ifdef WOLF_CRYPTO_CB
2738
#ifndef WOLF_CRYPTO_CB_FIND
2739
    if ((ret == 0) && (key->devId != INVALID_DEVID)) {
2740
#else
2741
    if (ret == 0) {
2742
#endif
2743
        ret = wc_CryptoCb_PqcDecapsulate(ct, ctSz, ss, WC_ML_KEM_SS_SZ,
2744
            WC_PQC_KEM_TYPE_MLKEM, key);
2745
        if (ret == WC_NO_ERR_TRACE(WC_PENDING_E))
2746
            ret = BAD_STATE_E; /* async unsupported for KEM decaps */
2747
        if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE))
2748
            return ret;
2749
        /* fall-through when unavailable */
2750
        ret = 0;
2751
    }
2752
#endif
2753
    /* Only software needs a local private key; a key named by id has none */
2754
0
    if ((ret == 0) && ((key->flags & MLKEM_FLAG_PRIV_SET) == 0)) {
2755
0
        ret = BAD_STATE_E;
2756
0
    }
2757
    /* Software decapsulation re-encrypts with the public key (FIPS 203,
2758
     * Algorithm 18, steps 2 and 8), so refuse before decrypting without it. */
2759
0
    if ((ret == 0) && ((key->flags & MLKEM_FLAG_PUB_SET) == 0)) {
2760
0
        ret = BAD_STATE_E;
2761
0
    }
2762
2763
#ifdef WOLF_CRYPTO_CB_ONLY_MLKEM
2764
    if (ret == 0) {
2765
        ret = NO_VALID_DEVID;
2766
    }
2767
#else
2768
2769
0
#ifndef WOLFSSL_MLKEM_ENCAPSULATE_SMALL_MEM
2770
0
#if defined(WOLFSSL_SMALL_STACK) || \
2771
0
    (!defined(USE_INTEL_SPEEDUP) && !defined(WOLFSSL_NO_MALLOC))
2772
0
    if (ret == 0) {
2773
        /* Allocate memory for cipher text that is generated. */
2774
0
        cmp = (byte*)XMALLOC(ctSz, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
2775
0
        if (cmp == NULL) {
2776
0
            ret = MEMORY_E;
2777
0
        }
2778
0
    }
2779
0
#endif
2780
0
#endif
2781
2782
    /* msg and kr hold secret decapsulation material; baseline-zero and register
2783
     * them here (below the crypto-callback early return) so any later exit
2784
     * before the ForceZero is covered. */
2785
#ifdef WOLFSSL_CHECK_MEM_ZERO
2786
    XMEMSET(msg, 0, sizeof(msg));
2787
    XMEMSET(kr, 0, sizeof(kr));
2788
    wc_MemZero_Add("mlkem decapsulate msg", msg, sizeof(msg));
2789
    wc_MemZero_Add("mlkem decapsulate kr", kr, sizeof(kr));
2790
    wc_MemZero_Add("mlkem decapsulate fail", &fail, sizeof(fail));
2791
    if (key != NULL) {
2792
        mlkemkey_hash_memzero_add(key);
2793
    }
2794
#endif
2795
#ifdef WC_MLKEM_NONBLOCK
2796
    if (ret == 0) {
2797
        /* Resume only the decapsulation of the cipher text here. */
2798
        if (mlkemkey_nb_begin(key, MLKEM_NB_OP_DECAP, NULL, 0, ct) == 1) {
2799
            WOLFSSL_MSG("ML-KEM non-blocking decapsulate starting");
2800
        } else {
2801
            WOLFSSL_MSG("ML-KEM non-blocking decapsulate resuming or unset");
2802
        }
2803
    }
2804
#endif
2805
    /* Decrypt and derive the re-encryption inputs. Runs once; a non-blocking
2806
     * resume carries msg and kr in the scratch and goes straight to the
2807
     * re-encryption. */
2808
#ifdef WC_MLKEM_NONBLOCK
2809
    if ((ret == 0) && ((key->nb == NULL) || (key->nb->state == 0)))
2810
#else
2811
0
    if (ret == 0)
2812
0
#endif
2813
0
    {
2814
        /* Decapsulate the cipher text. */
2815
0
        ret = mlkemkey_decapsulate(key, msg, ct);
2816
0
        if (ret == 0) {
2817
            /* Check we have H, hash of public, set. */
2818
0
            ret = wc_mlkemkey_check_h(key);
2819
0
        }
2820
0
        if (ret == 0) {
2821
            /* Hash message into seed buffer. */
2822
0
            ret = MLKEM_HASH_G(&key->hash, msg, WC_ML_KEM_SYM_SZ, key->h,
2823
0
                WC_ML_KEM_SYM_SZ, kr);
2824
0
        }
2825
#ifdef WC_MLKEM_NONBLOCK
2826
        if ((ret == 0) && (key->nb != NULL)) {
2827
            /* The re-encryption is compared with the cipher text a block per
2828
             * call: bind the operation to all of it. */
2829
            ret = MLKEM_HASH_H(&key->hash, ct, ctSz, key->nb->rand);
2830
        }
2831
        if ((ret == 0) && (key->nb != NULL)) {
2832
            /* msg and kr must outlive the per-row yields of re-encryption. */
2833
            if (key->nb->decWork != NULL) {
2834
                ForceZero(key->nb->decWork, key->nb->decWorkSz);
2835
                XFREE(key->nb->decWork, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
2836
            }
2837
            key->nb->decWork = XMALLOC(sizeof(msg) + 2 * WC_ML_KEM_SYM_SZ,
2838
                key->heap, DYNAMIC_TYPE_TMP_BUFFER);
2839
            if (key->nb->decWork == NULL) {
2840
                key->nb->decWorkSz = 0;
2841
                ret = MEMORY_E;
2842
            }
2843
            else {
2844
                key->nb->decWorkSz = (word32)(sizeof(msg) +
2845
                    2 * WC_ML_KEM_SYM_SZ);
2846
                XMEMCPY((byte*)key->nb->decWork, msg, sizeof(msg));
2847
                XMEMCPY((byte*)key->nb->decWork + sizeof(msg), kr,
2848
                    2 * WC_ML_KEM_SYM_SZ);
2849
                key->nb->state = 1;
2850
                ret = MP_WOULDBLOCK;
2851
            }
2852
        }
2853
#endif
2854
0
    }
2855
#ifdef WC_MLKEM_NONBLOCK
2856
    if ((ret == 0) && (key->nb != NULL) && (key->nb->state == 1)) {
2857
        XMEMCPY(msg, (byte*)key->nb->decWork, sizeof(msg));
2858
        XMEMCPY(kr, (byte*)key->nb->decWork + sizeof(msg),
2859
            2 * WC_ML_KEM_SYM_SZ);
2860
    }
2861
#endif
2862
0
    if (ret == 0) {
2863
        /* Encapsulate the message. Non-blocking, this yields per row and the
2864
         * compare completes on the call that finishes it. */
2865
0
#ifndef WOLFSSL_MLKEM_ENCAPSULATE_SMALL_MEM
2866
0
        ret = mlkemkey_encapsulate(key, msg, kr + WC_ML_KEM_SYM_SZ, cmp, NULL,
2867
0
            NULL);
2868
#else
2869
        ret = mlkemkey_encapsulate(key, msg, kr + WC_ML_KEM_SYM_SZ, NULL, ct,
2870
            &fail);
2871
#endif
2872
0
    }
2873
#ifdef WC_MLKEM_NONBLOCK
2874
    if ((ret == 0) && (key->nb != NULL)) {
2875
        /* The cipher text must still be the one the operation started on. */
2876
        byte ctHash[WC_ML_KEM_SYM_SZ];
2877
2878
        ret = MLKEM_HASH_H(&key->hash, ct, ctSz, ctHash);
2879
        if ((ret == 0) && (XMEMCMP(ctHash, key->nb->rand,
2880
                WC_ML_KEM_SYM_SZ) != 0)) {
2881
            ret = BAD_STATE_E;
2882
        }
2883
    }
2884
#endif
2885
0
#ifndef WOLFSSL_MLKEM_ENCAPSULATE_SMALL_MEM
2886
0
    if (ret == 0) {
2887
        /* Compare generated cipher text with that passed in. */
2888
0
        MLKEM_ARM64_SVR(ret = mlkem_cmp(ct, cmp, (int)ctSz, &fail));
2889
0
    }
2890
0
#endif
2891
0
    if (ret == 0) {
2892
#if defined(WOLFSSL_MLKEM_KYBER) && !defined(WOLFSSL_NO_ML_KEM)
2893
        if (key->type & MLKEM_KYBER)
2894
#endif
2895
#ifdef WOLFSSL_MLKEM_KYBER
2896
        {
2897
            /* Hash the cipher text after the seed. */
2898
            ret = MLKEM_HASH_H(&key->hash, ct, ctSz, kr + WC_ML_KEM_SYM_SZ);
2899
            if (ret == 0) {
2900
                /* Change seed to z on comparison failure. */
2901
                for (i = 0; i < WC_ML_KEM_SYM_SZ; i++) {
2902
                    kr[i] ^= (kr[i] ^ key->z[i]) & fail;
2903
                }
2904
2905
                /* Derive the secret from the seed and hash of cipher text. */
2906
                ret = MLKEM_KDF(kr, 2 * WC_ML_KEM_SYM_SZ, ss, WC_ML_KEM_SS_SZ);
2907
            }
2908
        }
2909
#endif
2910
#if defined(WOLFSSL_MLKEM_KYBER) && !defined(WOLFSSL_NO_ML_KEM)
2911
        else
2912
#endif
2913
0
#ifndef WOLFSSL_NO_ML_KEM
2914
0
        {
2915
0
            ret = mlkem_derive_secret(&key->prf, key->z, ct, ctSz, msg);
2916
0
            if (ret == 0) {
2917
               /* Set secret to kr or fake secret on comparison failure. */
2918
0
               for (i = 0; i < WC_ML_KEM_SYM_SZ; i++) {
2919
0
                   ss[i] = (byte)(kr[i] ^ ((kr[i] ^ msg[i]) & fail));
2920
0
               }
2921
0
            }
2922
0
        }
2923
0
#endif
2924
0
    }
2925
2926
0
#ifndef WOLFSSL_MLKEM_ENCAPSULATE_SMALL_MEM
2927
0
#if defined(WOLFSSL_SMALL_STACK) || \
2928
0
    (!defined(USE_INTEL_SPEEDUP) && !defined(WOLFSSL_NO_MALLOC))
2929
    /* Dispose of dynamic memory allocated in function. cmp holds the
2930
     * re-encrypted ciphertext computed from the secret decrypted message;
2931
     * zeroize before release - FIPS 203 section 3.3 (consistent with the PCT
2932
     * ciphertext handling in wc_MlKemKey_MakeKey). */
2933
0
    if (cmp != NULL) {
2934
0
        ForceZero(cmp, ctSz);
2935
0
        XFREE(cmp, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
2936
0
    }
2937
#else
2938
    /* cmp is a stack buffer holding the re-encrypted ciphertext; zeroize it. */
2939
    ForceZero(cmp, sizeof(cmp));
2940
#endif
2941
0
#endif
2942
#ifdef WC_MLKEM_NONBLOCK
2943
    if ((key != NULL) && (key->nb != NULL) &&
2944
            (ret != WC_NO_ERR_TRACE(MP_WOULDBLOCK))) {
2945
        /* Final success or error: release the carried msg and kr, and what a
2946
         * failure after a yield left of the re-encryption. */
2947
        mlkemkey_nb_release(key);
2948
    }
2949
#endif
2950
2951
0
    ForceZero(msg, sizeof(msg));
2952
0
    ForceZero(kr, sizeof(kr));
2953
    /* The implicit-rejection flag is destroyed too (FIPS 203 6.3). */
2954
0
    ForceZero(&fail, sizeof(fail));
2955
#ifdef WOLFSSL_CHECK_MEM_ZERO
2956
    wc_MemZero_Check(msg, sizeof(msg));
2957
    wc_MemZero_Check(kr, sizeof(kr));
2958
    wc_MemZero_Check(&fail, sizeof(fail));
2959
#endif
2960
0
    if (key != NULL) {
2961
0
        mlkemkey_hash_wipe(&key->hash);
2962
0
        mlkemkey_hash_wipe(&key->prf);
2963
    #ifdef WOLFSSL_CHECK_MEM_ZERO
2964
        mlkemkey_hash_memzero_check(key);
2965
    #endif
2966
0
    }
2967
0
#endif /* WOLF_CRYPTO_CB_ONLY_MLKEM */
2968
2969
0
    return ret;
2970
0
}
2971
#endif /* WOLFSSL_MLKEM_NO_DECAPSULATE */
2972
2973
/******************************************************************************/
2974
2975
/**
2976
 * Get the public key and public seed from bytes.
2977
 *
2978
 * FIPS 203, Algorithm 14: K-PKE.Encrypt(ek_PKE, m, r)
2979
 *   ...
2980
 *   2: t <- ByteDecode_12(ek_PKE[0 : 384k])
2981
 *   3: rho <- ek_PKE[384k :  384k + 32]
2982
 *   ...
2983
 *
2984
 * @param [out] pub      Public key - vector.
2985
 * @param [out] pubSeed  Public seed.
2986
 * @param [in]  p        Public key data.
2987
 * @param [in]  k        Number of polynomials in vector.
2988
 * @return  0 on success, or the error from a refused vector-register save.
2989
 */
2990
static int mlkemkey_decode_public(sword16* pub, byte* pubSeed, const byte* p,
2991
    unsigned int k)
2992
0
{
2993
0
    int ret;
2994
0
    unsigned int i;
2995
2996
    /* Decode public key that is vector of polynomials.
2997
     * Step 2: t <- ByteDecode_12(ek_PKE[0 : 384k]) */
2998
0
    ret = mlkem_from_bytes(pub, p, (int)k);
2999
0
    p += k * WC_ML_KEM_POLY_SIZE;
3000
3001
    /* Read public key seed.
3002
     * Step 3: rho <- ek_PKE[384k :  384k + 32] */
3003
0
    for (i = 0; i < WC_ML_KEM_SYM_SZ; i++) {
3004
0
        pubSeed[i] = p[i];
3005
0
    }
3006
0
    return ret;
3007
0
}
3008
3009
/**
3010
 * Decode the private key.
3011
 *
3012
 * Private Vector | Public Key | Public Hash | Randomizer
3013
 *
3014
 * FIPS 203, Algorithm 18: ML-KEM.Decaps_internal(dk, c)
3015
 *   1: dk_PKE <- dk[0 : 384k]
3016
 *                        > extract (from KEM decaps key) the PKE decryption key
3017
 *   2: ek_PKE <- dk[384k : 768k + 32]
3018
 *                                                  > extract PKE encryption key
3019
 *   3: h <- dk[768k + 32 : 768k + 64]
3020
 *                                          > extract hash of PKE encryption key
3021
 *   4: z <- dk[768k + 64 : 768k + 96]
3022
 *                                            > extract implicit rejection value
3023
 *
3024
 * FIPS 203, Algorithm 15: K-PKE.Decrypt(dk_PKE, c)
3025
 *   ...
3026
 *   5: s_hat <- ByteDecode_12(dk_PKE)
3027
 *   ...
3028
 *
3029
 * @param  [in, out]  key  ML-KEM key object.
3030
 * @param  [in]       in   Buffer holding encoded key.
3031
 * @param  [in]       len  Length of data in buffer.
3032
 * @return  0 on success.
3033
 * @return  BAD_FUNC_ARG when key or in is NULL.
3034
 * @return  NOT_COMPILED_IN when key type is not supported.
3035
 * @return  BUFFER_E when len is not the correct size.
3036
 * @return  PUBLIC_KEY_E when the private or public vector has a coefficient
3037
 *          that is not reduced modulo q, or public key data doesn't match
3038
 *          parameters.
3039
 * @return  MLKEM_PUB_HASH_E when public key hash doesn't match stored hash.
3040
 * @return  MEMORY_E when dynamic memory allocation failed.
3041
 */
3042
int wc_MlKemKey_DecodePrivateKey(MlKemKey* key, const unsigned char* in,
3043
    word32 len)
3044
0
{
3045
0
    int ret = 0;
3046
0
    word32 privLen = 0;
3047
0
    word32 pubLen = 0;
3048
0
    unsigned int k = 0;
3049
0
    const unsigned char* p = in;
3050
3051
    /* Validate parameters. */
3052
0
    if ((key == NULL) || (in == NULL)) {
3053
0
        ret = BAD_FUNC_ARG;
3054
0
    }
3055
3056
0
    if (ret == 0) {
3057
        /* Establish parameters based on key type. */
3058
0
        switch (key->type) {
3059
0
#ifndef WOLFSSL_NO_ML_KEM
3060
0
    #ifdef WOLFSSL_WC_ML_KEM_512
3061
0
        case WC_ML_KEM_512:
3062
0
            k = WC_ML_KEM_512_K;
3063
0
            privLen = WC_ML_KEM_512_PRIVATE_KEY_SIZE;
3064
0
            pubLen = WC_ML_KEM_512_PUBLIC_KEY_SIZE;
3065
0
            break;
3066
0
    #endif
3067
0
    #ifdef WOLFSSL_WC_ML_KEM_768
3068
0
        case WC_ML_KEM_768:
3069
0
            k = WC_ML_KEM_768_K;
3070
0
            privLen = WC_ML_KEM_768_PRIVATE_KEY_SIZE;
3071
0
            pubLen = WC_ML_KEM_768_PUBLIC_KEY_SIZE;
3072
0
            break;
3073
0
    #endif
3074
0
    #ifdef WOLFSSL_WC_ML_KEM_1024
3075
0
        case WC_ML_KEM_1024:
3076
0
            k = WC_ML_KEM_1024_K;
3077
0
            privLen = WC_ML_KEM_1024_PRIVATE_KEY_SIZE;
3078
0
            pubLen = WC_ML_KEM_1024_PUBLIC_KEY_SIZE;
3079
0
            break;
3080
0
    #endif
3081
0
#endif
3082
#ifdef WOLFSSL_MLKEM_KYBER
3083
    #ifdef WOLFSSL_KYBER512
3084
        case KYBER512:
3085
            k = KYBER512_K;
3086
            privLen = KYBER512_PRIVATE_KEY_SIZE;
3087
            pubLen = KYBER512_PUBLIC_KEY_SIZE;
3088
            break;
3089
    #endif
3090
    #ifdef WOLFSSL_KYBER768
3091
        case KYBER768:
3092
            k = KYBER768_K;
3093
            privLen = KYBER768_PRIVATE_KEY_SIZE;
3094
            pubLen = KYBER768_PUBLIC_KEY_SIZE;
3095
            break;
3096
    #endif
3097
    #ifdef WOLFSSL_KYBER1024
3098
        case KYBER1024:
3099
            k = KYBER1024_K;
3100
            privLen = KYBER1024_PRIVATE_KEY_SIZE;
3101
            pubLen = KYBER1024_PUBLIC_KEY_SIZE;
3102
            break;
3103
    #endif
3104
#endif
3105
0
        default:
3106
            /* No other values supported. */
3107
0
            ret = NOT_COMPILED_IN;
3108
0
            break;
3109
0
        }
3110
0
    }
3111
    /* Ensure the data is the correct length for the key type. */
3112
0
    if ((ret == 0) && (len != privLen)) {
3113
0
        ret = BUFFER_E;
3114
0
    }
3115
0
    if (ret == 0) {
3116
#ifdef WC_MLKEM_NONBLOCK
3117
        mlkemkey_nb_release(key);
3118
#endif
3119
        /* Forget the old key before its buffers are replaced, so a failure
3120
         * from here on leaves the key unusable. */
3121
0
        if (key->flags & MLKEM_FLAG_PRIV_SET) {
3122
            /* Do not write the new key over the old one. */
3123
0
#ifndef WOLFSSL_MLKEM_DYNAMIC_KEYS
3124
0
            ForceZero(key->priv, (size_t)k * MLKEM_N * sizeof(sword16));
3125
0
#endif
3126
0
            ForceZero(key->z, sizeof(key->z));
3127
0
        }
3128
0
        key->flags &= ~(MLKEM_FLAG_BOTH_SET | MLKEM_FLAG_H_SET |
3129
0
                        MLKEM_FLAG_A_SET);
3130
0
    }
3131
3132
#ifdef WOLFSSL_MLKEM_DYNAMIC_KEYS
3133
    if (ret == 0) {
3134
        ret = mlkemkey_alloc_priv(key, k);
3135
    }
3136
    if (ret == 0) {
3137
        ret = mlkemkey_alloc_pub(key, k);
3138
    }
3139
#endif
3140
0
    if (ret == 0) {
3141
        /* Decode private key that is vector of polynomials.
3142
         * Alg 18 Step 1: dk_PKE <- dk[0 : 384k]
3143
         * Alg 15 Step 5: s_hat <- ByteDecode_12(dk_PKE) */
3144
0
        ret = mlkem_from_bytes(key->priv, p, (int)k);
3145
0
        p += k * WC_ML_KEM_POLY_SIZE;
3146
3147
        /* Both vectors must decode to coefficients reduced modulo q. */
3148
0
        if (ret == 0) {
3149
0
            ret = mlkem_check_reduced(key->priv, (int)k);
3150
0
        }
3151
0
        if (ret == 0) {
3152
            /* Decode the public key that is after the private key. */
3153
0
            ret = mlkemkey_decode_public(key->pub, key->pubSeed, p, k);
3154
0
        }
3155
0
        if (ret == 0) {
3156
0
            ret = mlkem_check_reduced(key->pub, (int)k);
3157
0
        }
3158
0
        if (ret != 0) {
3159
0
            ForceZero(key->priv, k * MLKEM_N * sizeof(sword16));
3160
0
        }
3161
0
    }
3162
0
    if (ret == 0) {
3163
        /* Compute the hash of the public key. */
3164
0
        ret = MLKEM_HASH_H(&key->hash, p, pubLen, key->h);
3165
0
        if (ret != 0) {
3166
0
            ForceZero(key->priv, k * MLKEM_N * sizeof(sword16));
3167
0
        }
3168
0
    }
3169
3170
0
    if (ret == 0) {
3171
0
        p += pubLen;
3172
        /* Compare computed public key hash with stored hash */
3173
0
        if (XMEMCMP(key->h, p, WC_ML_KEM_SYM_SZ) != 0) {
3174
0
            ForceZero(key->priv, k * MLKEM_N * sizeof(sword16));
3175
0
            ret = MLKEM_PUB_HASH_E;
3176
0
        }
3177
0
    }
3178
3179
0
    if (ret == 0) {
3180
        /* Copy the hash of the encoded public key that is after public key. */
3181
0
        XMEMCPY(key->h, p, sizeof(key->h));
3182
0
        p += WC_ML_KEM_SYM_SZ;
3183
        /* Copy the z (randomizer) that is after hash. */
3184
0
        XMEMCPY(key->z, p, sizeof(key->z));
3185
3186
        /* Set flags */
3187
0
        key->flags |= MLKEM_FLAG_H_SET | MLKEM_FLAG_BOTH_SET;
3188
0
    }
3189
3190
0
    return ret;
3191
0
}
3192
3193
/**
3194
 * Decode public key.
3195
 *
3196
 * Public vector | Public Seed
3197
 *
3198
 * @param  [in, out]  key  ML-KEM key object.
3199
 * @param  [in]       in   Buffer holding encoded key.
3200
 * @param  [in]       len  Length of data in buffer.
3201
 * @return  0 on success.
3202
 * @return  BAD_FUNC_ARG when key or in is NULL.
3203
 * @return  NOT_COMPILED_IN when key type is not supported.
3204
 * @return  BUFFER_E when len is not the correct size.
3205
 * @return  PUBLIC_KEY_E when public key data doesn't match parameters.
3206
 * @return  MEMORY_E when dynamic memory allocation failed.
3207
 */
3208
int wc_MlKemKey_DecodePublicKey(MlKemKey* key, const unsigned char* in,
3209
    word32 len)
3210
0
{
3211
0
    int ret = 0;
3212
0
    word32 pubLen = 0;
3213
0
    unsigned int k = 0;
3214
0
    const unsigned char* p = in;
3215
0
    byte h[WC_ML_KEM_SYM_SZ];
3216
3217
0
    if ((key == NULL) || (in == NULL)) {
3218
0
        ret = BAD_FUNC_ARG;
3219
0
    }
3220
3221
0
    if (ret == 0) {
3222
        /* Establish parameters based on key type. */
3223
0
        switch (key->type) {
3224
0
#ifndef WOLFSSL_NO_ML_KEM
3225
0
    #ifdef WOLFSSL_WC_ML_KEM_512
3226
0
        case WC_ML_KEM_512:
3227
0
            k = WC_ML_KEM_512_K;
3228
0
            pubLen = WC_ML_KEM_512_PUBLIC_KEY_SIZE;
3229
0
            break;
3230
0
    #endif
3231
0
    #ifdef WOLFSSL_WC_ML_KEM_768
3232
0
        case WC_ML_KEM_768:
3233
0
            k = WC_ML_KEM_768_K;
3234
0
            pubLen = WC_ML_KEM_768_PUBLIC_KEY_SIZE;
3235
0
            break;
3236
0
    #endif
3237
0
    #ifdef WOLFSSL_WC_ML_KEM_1024
3238
0
        case WC_ML_KEM_1024:
3239
0
            k = WC_ML_KEM_1024_K;
3240
0
            pubLen = WC_ML_KEM_1024_PUBLIC_KEY_SIZE;
3241
0
            break;
3242
0
    #endif
3243
0
#endif
3244
#ifdef WOLFSSL_MLKEM_KYBER
3245
    #ifdef WOLFSSL_KYBER512
3246
        case KYBER512:
3247
            k = KYBER512_K;
3248
            pubLen = KYBER512_PUBLIC_KEY_SIZE;
3249
            break;
3250
    #endif
3251
    #ifdef WOLFSSL_KYBER768
3252
        case KYBER768:
3253
            k = KYBER768_K;
3254
            pubLen = KYBER768_PUBLIC_KEY_SIZE;
3255
            break;
3256
    #endif
3257
    #ifdef WOLFSSL_KYBER1024
3258
        case KYBER1024:
3259
            k = KYBER1024_K;
3260
            pubLen = KYBER1024_PUBLIC_KEY_SIZE;
3261
            break;
3262
    #endif
3263
#endif
3264
0
        default:
3265
            /* No other values supported. */
3266
0
            ret = NOT_COMPILED_IN;
3267
0
            break;
3268
0
        }
3269
0
    }
3270
    /* Ensure the data is the correct length for the key type. */
3271
0
    if ((ret == 0) && (len != pubLen)) {
3272
0
        ret = BUFFER_E;
3273
0
    }
3274
#ifdef WC_MLKEM_NONBLOCK
3275
    if (ret == 0) {
3276
        mlkemkey_nb_release(key);
3277
    }
3278
#endif
3279
0
    if ((ret == 0) && ((key->flags & MLKEM_FLAG_PRIV_SET) != 0)) {
3280
        /* Make sure key->h is H(ek) of the private key's own public key. */
3281
0
        ret = wc_mlkemkey_check_h(key);
3282
0
    }
3283
0
    if (ret == 0) {
3284
0
        ret = MLKEM_HASH_H(&key->hash, in, len, h);
3285
0
    }
3286
0
    if (ret == 0) {
3287
        /* Wipe a private key that does not match the new public key. */
3288
0
        if (((key->flags & MLKEM_FLAG_PRIV_SET) != 0) &&
3289
0
                (XMEMCMP(h, key->h, WC_ML_KEM_SYM_SZ) != 0)) {
3290
        #ifdef WOLFSSL_MLKEM_DYNAMIC_KEYS
3291
            if (key->priv != NULL) {
3292
                ForceZero(key->priv, key->privAllocSz);
3293
            }
3294
        #else
3295
0
            ForceZero(key->priv, sizeof(key->priv));
3296
0
        #endif
3297
0
            ForceZero(key->z, WC_ML_KEM_SYM_SZ);
3298
0
            key->flags &= ~MLKEM_FLAG_PRIV_SET;
3299
0
        }
3300
        /* Forget the old public key and its cached matrix before they are
3301
         * replaced, so a failure from here on leaves no public key. */
3302
0
        key->flags &= ~(MLKEM_FLAG_PUB_SET | MLKEM_FLAG_A_SET);
3303
        /* A kept private key still matches key->h, so a retry can compare. */
3304
0
        if ((key->flags & MLKEM_FLAG_PRIV_SET) == 0) {
3305
0
            key->flags &= ~MLKEM_FLAG_H_SET;
3306
0
        }
3307
0
    }
3308
3309
#ifdef WOLFSSL_MLKEM_DYNAMIC_KEYS
3310
    if (ret == 0) {
3311
        ret = mlkemkey_alloc_pub(key, k);
3312
    }
3313
#endif
3314
0
    if (ret == 0) {
3315
        /* Decode public key and check public key matches parameters. */
3316
0
        ret = mlkemkey_decode_public(key->pub, key->pubSeed, p, k);
3317
0
    }
3318
0
    if (ret == 0) {
3319
0
        ret = mlkem_check_reduced(key->pub, (int)k);
3320
0
    }
3321
0
    if (ret == 0) {
3322
0
        XMEMCPY(key->h, h, WC_ML_KEM_SYM_SZ);
3323
        /* Record public key and public hash set. */
3324
0
        key->flags |= MLKEM_FLAG_PUB_SET | MLKEM_FLAG_H_SET;
3325
0
    }
3326
3327
0
    return ret;
3328
0
}
3329
3330
/**
3331
 * Get the size in bytes of encoded private key for the key.
3332
 *
3333
 * @param  [in]   key  ML-KEM key object.
3334
 * @param  [out]  len  Length of encoded private key in bytes.
3335
 * @return  0 on success.
3336
 * @return  BAD_FUNC_ARG when key or len is NULL.
3337
 * @return  NOT_COMPILED_IN when key type is not supported.
3338
 */
3339
int wc_MlKemKey_PrivateKeySize(MlKemKey* key, word32* len)
3340
0
{
3341
0
    int ret = 0;
3342
3343
    /* Validate parameters. */
3344
0
    if ((key == NULL) || (len == NULL)) {
3345
0
        ret = BAD_FUNC_ARG;
3346
0
    }
3347
3348
0
    if (ret == 0) {
3349
        /* Return in 'len' size of the encoded private key for the type of this
3350
         * key. */
3351
0
        switch (key->type) {
3352
0
#ifndef WOLFSSL_NO_ML_KEM
3353
0
    #ifdef WOLFSSL_WC_ML_KEM_512
3354
0
        case WC_ML_KEM_512:
3355
0
            *len = WC_ML_KEM_512_PRIVATE_KEY_SIZE;
3356
0
            break;
3357
0
    #endif
3358
0
    #ifdef WOLFSSL_WC_ML_KEM_768
3359
0
        case WC_ML_KEM_768:
3360
0
            *len = WC_ML_KEM_768_PRIVATE_KEY_SIZE;
3361
0
            break;
3362
0
    #endif
3363
0
    #ifdef WOLFSSL_WC_ML_KEM_1024
3364
0
        case WC_ML_KEM_1024:
3365
0
            *len = WC_ML_KEM_1024_PRIVATE_KEY_SIZE;
3366
0
            break;
3367
0
    #endif
3368
0
#endif
3369
#ifdef WOLFSSL_MLKEM_KYBER
3370
    #ifdef WOLFSSL_KYBER512
3371
        case KYBER512:
3372
            *len = KYBER512_PRIVATE_KEY_SIZE;
3373
            break;
3374
    #endif
3375
    #ifdef WOLFSSL_KYBER768
3376
        case KYBER768:
3377
            *len = KYBER768_PRIVATE_KEY_SIZE;
3378
            break;
3379
    #endif
3380
    #ifdef WOLFSSL_KYBER1024
3381
        case KYBER1024:
3382
            *len = KYBER1024_PRIVATE_KEY_SIZE;
3383
            break;
3384
    #endif
3385
#endif
3386
0
        default:
3387
            /* No other values supported. */
3388
0
            ret = NOT_COMPILED_IN;
3389
0
            break;
3390
0
        }
3391
0
    }
3392
3393
0
    return ret;
3394
0
}
3395
3396
/**
3397
 * Get the size in bytes of encoded public key for the key.
3398
 *
3399
 * @param  [in]   key  ML-KEM key object.
3400
 * @param  [out]  len  Length of encoded public key in bytes.
3401
 * @return  0 on success.
3402
 * @return  BAD_FUNC_ARG when key or len is NULL.
3403
 * @return  NOT_COMPILED_IN when key type is not supported.
3404
 */
3405
int wc_MlKemKey_PublicKeySize(MlKemKey* key, word32* len)
3406
0
{
3407
0
    int ret = 0;
3408
3409
    /* Validate parameters. */
3410
0
    if ((key == NULL) || (len == NULL)) {
3411
0
        ret = BAD_FUNC_ARG;
3412
0
    }
3413
3414
0
    if (ret == 0) {
3415
        /* Return in 'len' size of the encoded public key for the type of this
3416
         * key. */
3417
0
        switch (key->type) {
3418
0
#ifndef WOLFSSL_NO_ML_KEM
3419
0
    #ifdef WOLFSSL_WC_ML_KEM_512
3420
0
        case WC_ML_KEM_512:
3421
0
            *len = WC_ML_KEM_512_PUBLIC_KEY_SIZE;
3422
0
            break;
3423
0
    #endif
3424
0
    #ifdef WOLFSSL_WC_ML_KEM_768
3425
0
        case WC_ML_KEM_768:
3426
0
            *len = WC_ML_KEM_768_PUBLIC_KEY_SIZE;
3427
0
            break;
3428
0
    #endif
3429
0
    #ifdef WOLFSSL_WC_ML_KEM_1024
3430
0
        case WC_ML_KEM_1024:
3431
0
            *len = WC_ML_KEM_1024_PUBLIC_KEY_SIZE;
3432
0
            break;
3433
0
    #endif
3434
0
#endif
3435
#ifdef WOLFSSL_MLKEM_KYBER
3436
    #ifdef WOLFSSL_KYBER512
3437
        case KYBER512:
3438
            *len = KYBER512_PUBLIC_KEY_SIZE;
3439
            break;
3440
    #endif
3441
    #ifdef WOLFSSL_KYBER768
3442
        case KYBER768:
3443
            *len = KYBER768_PUBLIC_KEY_SIZE;
3444
            break;
3445
    #endif
3446
    #ifdef WOLFSSL_KYBER1024
3447
        case KYBER1024:
3448
            *len = KYBER1024_PUBLIC_KEY_SIZE;
3449
            break;
3450
    #endif
3451
#endif
3452
0
        default:
3453
            /* No other values supported. */
3454
0
            ret = NOT_COMPILED_IN;
3455
0
            break;
3456
0
        }
3457
0
    }
3458
3459
0
    return ret;
3460
0
}
3461
3462
/**
3463
 * Encode the private key.
3464
 *
3465
 * Private Vector | Public Key | Public Hash | Randomizer
3466
 *
3467
 * FIPS 203, Algorithm 16: ML-KEM.KeyGen_internal(d,z)
3468
 *   ...
3469
 *   3: dk <- (dk_PKE||ek||H(ek)||z)
3470
 *   ...
3471
 * FIPS 203, Algorithm 13: K-PKE.KeyGen(d)
3472
 *   ...
3473
 *   20: dk_PKE  <- ByteEncode_12(s_hat)
3474
 *   ...
3475
 *
3476
 * @param  [in]   key  ML-KEM key object.
3477
 * @param  [out]  out  Buffer to hold data.
3478
 * @param  [in]   len  Size of buffer in bytes.
3479
 * @return  0 on success.
3480
 * @return  BAD_FUNC_ARG when key or out is NULL.
3481
 * @return  BAD_STATE_E when private/public key not available.
3482
 * @return  NOT_COMPILED_IN when key type is not supported.
3483
 */
3484
int wc_MlKemKey_EncodePrivateKey(MlKemKey* key, unsigned char* out, word32 len)
3485
0
{
3486
0
    int ret = 0;
3487
0
    unsigned int k = 0;
3488
0
    unsigned int pubLen = 0;
3489
0
    unsigned int privLen = 0;
3490
0
    unsigned char* p = out;
3491
3492
0
    if ((key == NULL) || (out == NULL)) {
3493
0
        ret = BAD_FUNC_ARG;
3494
0
    }
3495
0
    if ((ret == 0) &&
3496
0
            ((key->flags & MLKEM_FLAG_BOTH_SET) != MLKEM_FLAG_BOTH_SET)) {
3497
0
        ret = BAD_STATE_E;
3498
0
    }
3499
3500
0
    if (ret == 0) {
3501
0
        switch (key->type) {
3502
0
#ifndef WOLFSSL_NO_ML_KEM
3503
0
    #ifdef WOLFSSL_WC_ML_KEM_512
3504
0
        case WC_ML_KEM_512:
3505
0
            k = WC_ML_KEM_512_K;
3506
0
            pubLen = WC_ML_KEM_512_PUBLIC_KEY_SIZE;
3507
0
            privLen = WC_ML_KEM_512_PRIVATE_KEY_SIZE;
3508
0
            break;
3509
0
    #endif
3510
0
    #ifdef WOLFSSL_WC_ML_KEM_768
3511
0
        case WC_ML_KEM_768:
3512
0
            k = WC_ML_KEM_768_K;
3513
0
            pubLen = WC_ML_KEM_768_PUBLIC_KEY_SIZE;
3514
0
            privLen = WC_ML_KEM_768_PRIVATE_KEY_SIZE;
3515
0
            break;
3516
0
    #endif
3517
0
    #ifdef WOLFSSL_WC_ML_KEM_1024
3518
0
        case WC_ML_KEM_1024:
3519
0
            k = WC_ML_KEM_1024_K;
3520
0
            pubLen = WC_ML_KEM_1024_PUBLIC_KEY_SIZE;
3521
0
            privLen = WC_ML_KEM_1024_PRIVATE_KEY_SIZE;
3522
0
            break;
3523
0
    #endif
3524
0
#endif
3525
#ifdef WOLFSSL_MLKEM_KYBER
3526
    #ifdef WOLFSSL_KYBER512
3527
        case KYBER512:
3528
            k = KYBER512_K;
3529
            pubLen = KYBER512_PUBLIC_KEY_SIZE;
3530
            privLen = KYBER512_PRIVATE_KEY_SIZE;
3531
            break;
3532
    #endif
3533
    #ifdef WOLFSSL_KYBER768
3534
        case KYBER768:
3535
            k = KYBER768_K;
3536
            pubLen = KYBER768_PUBLIC_KEY_SIZE;
3537
            privLen = KYBER768_PRIVATE_KEY_SIZE;
3538
            break;
3539
    #endif
3540
    #ifdef WOLFSSL_KYBER1024
3541
        case KYBER1024:
3542
            k = KYBER1024_K;
3543
            pubLen = KYBER1024_PUBLIC_KEY_SIZE;
3544
            privLen = KYBER1024_PRIVATE_KEY_SIZE;
3545
            break;
3546
    #endif
3547
#endif
3548
0
        default:
3549
            /* No other values supported. */
3550
0
            ret = NOT_COMPILED_IN;
3551
0
            break;
3552
0
        }
3553
0
    }
3554
    /* Check buffer is big enough for encoding. */
3555
0
    if ((ret == 0) && (len != privLen)) {
3556
0
        ret = BUFFER_E;
3557
0
    }
3558
3559
0
    if (ret == 0) {
3560
        /* Encode private key that is vector of polynomials. */
3561
0
        MLKEM_ARM64_SVR(ret = mlkem_to_bytes(p, key->priv, (int)k));
3562
0
    }
3563
0
    if (ret == 0) {
3564
0
        p += WC_ML_KEM_POLY_SIZE * k;
3565
3566
        /* Encode public key - calculates hash of public key. */
3567
0
        ret = wc_MlKemKey_EncodePublicKey(key, p, pubLen);
3568
0
        p += pubLen;
3569
0
        if (ret != 0) {
3570
            /* s_hat is already in the buffer. */
3571
0
            ForceZero(out, privLen);
3572
0
        }
3573
0
    }
3574
0
    if (ret == 0) {
3575
        /* Append public hash. */
3576
0
        XMEMCPY(p, key->h, sizeof(key->h));
3577
0
        p += WC_ML_KEM_SYM_SZ;
3578
        /* Append z (randomizer). */
3579
0
        XMEMCPY(p, key->z, sizeof(key->z));
3580
0
    }
3581
3582
0
    return ret;
3583
0
}
3584
3585
/**
3586
 * Encode the public key.
3587
 *
3588
 * Public vector | Public Seed
3589
 *
3590
 * FIPS 203, Algorithm 16: ML-KEM.KeyGen_internal(d,z)
3591
 *   ...
3592
 *   2: ek <- ek_PKE
3593
 *   ...
3594
 * FIPS 203, Algorithm 13: K-PKE.KeyGen(d)
3595
 *   ...
3596
 *   19: ek_PKE  <- ByteEncode_12(t_hat)||rho
3597
 *   ...
3598
 *
3599
 * @param  [in]   key  ML-KEM key object.
3600
 * @param  [out]  out  Buffer to hold data.
3601
 * @param  [in]   len  Size of buffer in bytes.
3602
 * @return  0 on success.
3603
 * @return  BAD_FUNC_ARG when key or out is NULL.
3604
 * @return  BAD_STATE_E when public key not available.
3605
 * @return  NOT_COMPILED_IN when key type is not supported.
3606
 */
3607
int wc_MlKemKey_EncodePublicKey(MlKemKey* key, unsigned char* out, word32 len)
3608
0
{
3609
0
    int ret = 0;
3610
0
    unsigned int k = 0;
3611
0
    unsigned int pubLen = 0;
3612
0
    unsigned char* p = out;
3613
3614
0
    if ((key == NULL) || (out == NULL)) {
3615
0
        ret = BAD_FUNC_ARG;
3616
0
    }
3617
0
    if ((ret == 0) &&
3618
0
            ((key->flags & MLKEM_FLAG_PUB_SET) != MLKEM_FLAG_PUB_SET)) {
3619
0
        ret = BAD_STATE_E;
3620
0
    }
3621
3622
0
    if (ret == 0) {
3623
0
        switch (key->type) {
3624
0
#ifndef WOLFSSL_NO_ML_KEM
3625
0
    #ifdef WOLFSSL_WC_ML_KEM_512
3626
0
        case WC_ML_KEM_512:
3627
0
            k = WC_ML_KEM_512_K;
3628
0
            pubLen = WC_ML_KEM_512_PUBLIC_KEY_SIZE;
3629
0
            break;
3630
0
    #endif
3631
0
    #ifdef WOLFSSL_WC_ML_KEM_768
3632
0
        case WC_ML_KEM_768:
3633
0
            k = WC_ML_KEM_768_K;
3634
0
            pubLen = WC_ML_KEM_768_PUBLIC_KEY_SIZE;
3635
0
            break;
3636
0
    #endif
3637
0
    #ifdef WOLFSSL_WC_ML_KEM_1024
3638
0
        case WC_ML_KEM_1024:
3639
0
            k = WC_ML_KEM_1024_K;
3640
0
            pubLen = WC_ML_KEM_1024_PUBLIC_KEY_SIZE;
3641
0
            break;
3642
0
    #endif
3643
0
#endif
3644
#ifdef WOLFSSL_MLKEM_KYBER
3645
    #ifdef WOLFSSL_KYBER512
3646
        case KYBER512:
3647
            k = KYBER512_K;
3648
            pubLen = KYBER512_PUBLIC_KEY_SIZE;
3649
            break;
3650
    #endif
3651
    #ifdef WOLFSSL_KYBER768
3652
        case KYBER768:
3653
            k = KYBER768_K;
3654
            pubLen = KYBER768_PUBLIC_KEY_SIZE;
3655
            break;
3656
    #endif
3657
    #ifdef WOLFSSL_KYBER1024
3658
        case KYBER1024:
3659
            k = KYBER1024_K;
3660
            pubLen = KYBER1024_PUBLIC_KEY_SIZE;
3661
            break;
3662
    #endif
3663
#endif
3664
0
        default:
3665
            /* No other values supported. */
3666
0
            ret = NOT_COMPILED_IN;
3667
0
            break;
3668
0
        }
3669
0
    }
3670
    /* Check buffer is big enough for encoding. */
3671
0
    if ((ret == 0) && (len != pubLen)) {
3672
0
        ret = BUFFER_E;
3673
0
    }
3674
3675
0
    if (ret == 0) {
3676
        /* Encode public key polynomial by polynomial. */
3677
0
        MLKEM_ARM64_SVR(ret = mlkem_to_bytes(p, key->pub, (int)k));
3678
0
    }
3679
0
    if (ret == 0) {
3680
0
        int i;
3681
3682
0
        p += k * WC_ML_KEM_POLY_SIZE;
3683
3684
        /* Append public seed. */
3685
0
        for (i = 0; i < WC_ML_KEM_SYM_SZ; i++) {
3686
0
            p[i] = key->pubSeed[i];
3687
0
        }
3688
3689
        /* Make sure public hash is set. */
3690
0
        if ((key->flags & MLKEM_FLAG_H_SET) == 0) {
3691
0
            ret = MLKEM_HASH_H(&key->hash, out, len, key->h);
3692
0
        }
3693
0
    }
3694
0
    if (ret == 0) {
3695
        /* Public hash is set. wc_mlkemkey_check_h() relies on this happening on
3696
         * every successful path: it calls this function to establish the flag
3697
         * and does not test it again afterwards. */
3698
0
        key->flags |= MLKEM_FLAG_H_SET;
3699
0
    }
3700
3701
0
    return ret;
3702
0
}
3703
3704
#ifndef WOLFSSL_MLKEM_NO_ASN1
3705
#if defined(WC_ENABLE_ASYM_KEY_EXPORT) || defined(WC_ENABLE_ASYM_KEY_IMPORT)
3706
3707
/* Map an ML-KEM key type to its FIPS 203 key-OID sum.
3708
 *
3709
 * @param  [in]   type    ML-KEM key type (WC_ML_KEM_512/768/1024).
3710
 * @param  [out]  oidSum  OID sum (ML_KEM_512k/768k/1024k).
3711
 * @return  0 on success.
3712
 * @return  BAD_FUNC_ARG when the type is not an ML-KEM parameter set.
3713
 */
3714
static int mlkem_type_to_oid_sum(int type, int* oidSum)
3715
0
{
3716
0
    int ret = 0;
3717
3718
0
    switch (type) {
3719
0
        case WC_ML_KEM_512:
3720
0
            *oidSum = ML_KEM_512k;
3721
0
            break;
3722
0
        case WC_ML_KEM_768:
3723
0
            *oidSum = ML_KEM_768k;
3724
0
            break;
3725
0
        case WC_ML_KEM_1024:
3726
0
            *oidSum = ML_KEM_1024k;
3727
0
            break;
3728
0
        default:
3729
            /* Kyber round-3 types have no standardised OID. */
3730
0
            ret = BAD_FUNC_ARG;
3731
0
            break;
3732
0
    }
3733
3734
0
    return ret;
3735
0
}
3736
3737
#endif /* WC_ENABLE_ASYM_KEY_EXPORT || WC_ENABLE_ASYM_KEY_IMPORT */
3738
3739
/* Map an ML-KEM key-OID sum to its parameter set.
3740
 *
3741
 * The inverse of mlkem_type_to_oid_sum, for callers that already hold the OID
3742
 * and want to pin the key to it rather than let a decode adopt one.
3743
 *
3744
 * @param  [in]   oidSum  OID sum (ML_KEM_512k/768k/1024k).
3745
 * @param  [out]  type    ML-KEM key type (WC_ML_KEM_512/768/1024).
3746
 * @return  0 on success.
3747
 * @return  BAD_FUNC_ARG when type is NULL or the OID is not an ML-KEM key OID.
3748
 */
3749
int mlkem_type_from_oid_sum(int oidSum, int* type)
3750
0
{
3751
0
    int ret = 0;
3752
3753
0
    if (type == NULL)
3754
0
        return BAD_FUNC_ARG;
3755
3756
0
    switch (oidSum) {
3757
0
        case ML_KEM_512k:
3758
0
            *type = WC_ML_KEM_512;
3759
0
            break;
3760
0
        case ML_KEM_768k:
3761
0
            *type = WC_ML_KEM_768;
3762
0
            break;
3763
0
        case ML_KEM_1024k:
3764
0
            *type = WC_ML_KEM_1024;
3765
0
            break;
3766
0
        default:
3767
0
            ret = BAD_FUNC_ARG;
3768
0
            break;
3769
0
    }
3770
3771
0
    return ret;
3772
0
}
3773
3774
#ifdef WC_ENABLE_ASYM_KEY_EXPORT
3775
/* Encode the ML-KEM public key as a DER SubjectPublicKeyInfo.
3776
 *
3777
 * Pass NULL for output to get the size of the encoding.
3778
 *
3779
 * @param  [in]   key      ML-KEM key object with public key set.
3780
 * @param  [out]  output   Buffer for the DER, or NULL to get the length.
3781
 * @param  [in]   len      Size of output buffer in bytes.
3782
 * @param  [in]   withAlg  Include the SubjectPublicKeyInfo wrapper (1) or emit
3783
 *                         only the raw public key bytes (0).
3784
 * @return  Length of the encoding in bytes on success.
3785
 * @return  BAD_FUNC_ARG when key is NULL or the type has no OID.
3786
 * @return  MEMORY_E when dynamic memory allocation fails.
3787
 */
3788
int wc_MlKemKey_PublicKeyToDer(MlKemKey* key, byte* output, word32 len,
3789
    int withAlg)
3790
0
{
3791
0
    int ret = 0;
3792
0
    int oidSum = 0;
3793
0
    word32 pubLen = 0;
3794
0
    int sz = 0;
3795
3796
0
    if (key == NULL)
3797
0
        return BAD_FUNC_ARG;
3798
3799
0
    if (ret == 0) {
3800
0
        ret = mlkem_type_to_oid_sum(key->type, &oidSum);
3801
0
    }
3802
0
    if (ret == 0) {
3803
0
        ret = wc_MlKemKey_PublicKeySize(key, &pubLen);
3804
0
    }
3805
0
    if (ret == 0) {
3806
        /* Length of the encoding. pubKey is only read when output is given,
3807
         * so any non-NULL pointer satisfies the argument check here. */
3808
0
        sz = SetAsymKeyDerPublic((const byte*)key, pubLen, NULL, 0, oidSum,
3809
0
            withAlg);
3810
0
        if (sz < 0)
3811
0
            ret = sz;
3812
0
    }
3813
0
    if ((ret == 0) && (output != NULL)) {
3814
0
        if (len < (word32)sz) {
3815
0
            ret = BUFFER_E;
3816
0
        }
3817
0
        else {
3818
            /* The raw key is the last field of the encoding, so write it
3819
             * where it will live and let the header be built around it. That
3820
             * is what removes the temporary, and with it the need for a heap
3821
             * in a WOLFSSL_NO_MALLOC build. */
3822
0
            ret = wc_MlKemKey_EncodePublicKey(key,
3823
0
                output + ((word32)sz - pubLen), pubLen);
3824
0
        }
3825
0
    }
3826
0
    if ((ret == 0) && (output != NULL)) {
3827
0
        ret = SetAsymKeyDerPublic(output + ((word32)sz - pubLen), pubLen,
3828
0
            output, len, oidSum, withAlg);
3829
0
    }
3830
0
    else if (ret == 0) {
3831
0
        ret = sz;
3832
0
    }
3833
3834
0
    return ret;
3835
0
}
3836
3837
/* Encode the ML-KEM private key as a DER PKCS#8 OneAsymmetricKey.
3838
 *
3839
 * The expanded decapsulation key is emitted. The seed and seed-with-expanded
3840
 * alternatives of the ML-KEM private key are not produced.
3841
 *
3842
 * Pass NULL for output to get the size of the encoding.
3843
 *
3844
 * @param  [in]   key     ML-KEM key object with private key set.
3845
 * @param  [out]  output  Buffer for the DER, or NULL to get the length.
3846
 * @param  [in]   len     Size of output buffer in bytes.
3847
 * @return  Length of the encoding in bytes on success.
3848
 * @return  BAD_FUNC_ARG when key is NULL or the type has no OID.
3849
 * @return  MEMORY_E when dynamic memory allocation fails.
3850
 */
3851
int wc_MlKemKey_PrivateKeyToDer(MlKemKey* key, byte* output, word32 len)
3852
0
{
3853
0
    int ret = 0;
3854
0
    int oidSum = 0;
3855
0
    word32 privLen = 0;
3856
0
    int sz = 0;
3857
3858
0
    if (key == NULL)
3859
0
        return BAD_FUNC_ARG;
3860
3861
0
    if (ret == 0) {
3862
0
        ret = mlkem_type_to_oid_sum(key->type, &oidSum);
3863
0
    }
3864
0
    if (ret == 0) {
3865
0
        ret = wc_MlKemKey_PrivateKeySize(key, &privLen);
3866
0
    }
3867
0
    if (ret == 0) {
3868
        /* Length of the encoding. privKey is only read when output is given,
3869
         * so any non-NULL pointer satisfies the argument check here. The
3870
         * ML-KEM private key embeds the public key, so none is appended. */
3871
0
        sz = SetAsymKeyDer((const byte*)key, privLen, NULL, 0, NULL, 0,
3872
0
            oidSum);
3873
0
        if (sz < 0)
3874
0
            ret = sz;
3875
0
    }
3876
0
    if ((ret == 0) && (output != NULL)) {
3877
0
        if (len < (word32)sz) {
3878
0
            ret = BUFFER_E;
3879
0
        }
3880
0
        else {
3881
            /* Written where it will live, so the header is built around it
3882
             * and no temporary is needed. See wc_MlKemKey_PublicKeyToDer. */
3883
0
            ret = wc_MlKemKey_EncodePrivateKey(key,
3884
0
                output + ((word32)sz - privLen), privLen);
3885
0
        }
3886
0
    }
3887
0
    if ((ret == 0) && (output != NULL)) {
3888
0
        ret = SetAsymKeyDer(output + ((word32)sz - privLen), privLen, NULL, 0,
3889
0
            output, len, oidSum);
3890
0
        if (ret < 0) {
3891
0
            ForceZero(output + ((word32)sz - privLen), privLen);
3892
0
        }
3893
0
    }
3894
0
    else if (ret == 0) {
3895
0
        ret = sz;
3896
0
    }
3897
3898
0
    return ret;
3899
0
}
3900
#endif /* WC_ENABLE_ASYM_KEY_EXPORT */
3901
3902
#ifdef WC_ENABLE_ASYM_KEY_IMPORT
3903
/* Take the parameter set from a DER algorithm OID sum.
3904
 *
3905
 * @param  [in, out]  key     ML-KEM key object with no parameter set yet.
3906
 * @param  [in]       oidSum  Key OID sum read from the DER.
3907
 * @return  0 on success.
3908
 * @return  BAD_FUNC_ARG when the OID is not an ML-KEM key OID.
3909
 * @return  NOT_COMPILED_IN when the parameter set is not in this build.
3910
 */
3911
static int mlkem_key_adopt_type(MlKemKey* key, int oidSum)
3912
0
{
3913
0
    int type = 0;
3914
0
    int ret = mlkem_type_from_oid_sum(oidSum, &type);
3915
3916
0
    if (ret == 0) {
3917
0
        switch (type) {
3918
0
#ifndef WOLFSSL_NO_ML_KEM
3919
0
    #ifdef WOLFSSL_WC_ML_KEM_512
3920
0
        case WC_ML_KEM_512:
3921
0
            break;
3922
0
    #endif
3923
0
    #ifdef WOLFSSL_WC_ML_KEM_768
3924
0
        case WC_ML_KEM_768:
3925
0
            break;
3926
0
    #endif
3927
0
    #ifdef WOLFSSL_WC_ML_KEM_1024
3928
0
        case WC_ML_KEM_1024:
3929
0
            break;
3930
0
    #endif
3931
0
#endif
3932
0
        default:
3933
0
            ret = NOT_COMPILED_IN;
3934
0
            break;
3935
0
        }
3936
0
    }
3937
0
    if (ret == 0) {
3938
0
        key->type = type;
3939
0
        key->flags |= MLKEM_FLAG_TYPE_SET;
3940
0
    }
3941
3942
0
    return ret;
3943
0
}
3944
3945
/* Decode a DER SubjectPublicKeyInfo into an ML-KEM public key.
3946
 *
3947
 * Takes wrapped DER, unlike wc_MlKemKey_DecodePublicKey which takes the raw
3948
 * encoded key. A key initialized for a parameter set holds the DER to it; one
3949
 * initialized WC_ML_KEM_TYPE_UNSET takes it from the algorithm OID.
3950
 *
3951
 * @param  [in, out]  key       ML-KEM key object.
3952
 * @param  [in]       input     DER buffer.
3953
 * @param  [in]       inSz      Size of DER buffer in bytes.
3954
 * @param  [in, out]  inOutIdx  On in, index into buffer; on out, index after.
3955
 * @return  0 on success.
3956
 * @return  BAD_FUNC_ARG when a pointer is NULL.
3957
 * @return  ASN_PARSE_E when the DER is invalid or names another parameter set.
3958
 */
3959
int wc_MlKemKey_PublicKeyDecode(MlKemKey* key, const byte* input, word32 inSz,
3960
    word32* inOutIdx)
3961
0
{
3962
0
    int ret = 0;
3963
0
    int keyType = ANONk;
3964
0
    const byte* pubKey = NULL;
3965
0
    word32 pubKeyLen = 0;
3966
3967
0
    if ((key == NULL) || (input == NULL) || (inOutIdx == NULL)) {
3968
0
        ret = BAD_FUNC_ARG;
3969
0
    }
3970
0
    if ((ret == 0) && ((key->flags & MLKEM_FLAG_TYPE_SET) != 0)) {
3971
        /* A parameter set was named at init, so hold the DER to it. */
3972
0
        ret = mlkem_type_to_oid_sum(key->type, &keyType);
3973
0
    }
3974
0
    if (ret == 0) {
3975
        /* keyType is ANONk when none was named, which auto-detects. */
3976
0
        ret = DecodeAsymKeyPublic_Assign(input, inOutIdx, inSz, &pubKey,
3977
0
            &pubKeyLen, &keyType);
3978
0
    }
3979
0
    if ((ret == 0) && ((key->flags & MLKEM_FLAG_TYPE_SET) == 0)) {
3980
0
        ret = mlkem_key_adopt_type(key, keyType);
3981
0
    }
3982
0
    if (ret == 0) {
3983
0
        ret = wc_MlKemKey_DecodePublicKey(key, pubKey, pubKeyLen);
3984
0
    }
3985
3986
0
    return ret;
3987
0
}
3988
3989
#if defined(WOLFSSL_MLKEM_NO_MAKE_KEY) || defined(WOLF_CRYPTO_CB_ONLY_MLKEM)
3990
    #define MLKEM_NO_SEED_EXPAND
3991
#endif
3992
3993
/* Decode a DER PKCS#8 OneAsymmetricKey into an ML-KEM private key.
3994
 *
3995
 * All three RFC 9935 Section 6 CHOICE shapes are accepted: the 64 byte seed
3996
 * under an implicit [0], the expanded decapsulation key as an OCTET STRING,
3997
 * and the SEQUENCE carrying both. A seed is expanded with
3998
 * ML-KEM.KeyGen_internal(d,z); when both forms are present the expanded key
3999
 * is regenerated from the seed and the two are compared, per RFC 9935
4000
 * Section 8. The parameter set must match the initialized key object, as
4001
 * described for wc_MlKemKey_PublicKeyDecode.
4002
 *
4003
 * A WOLFSSL_MLKEM_NO_MAKE_KEY or WOLF_CRYPTO_CB_ONLY_MLKEM build cannot
4004
 * expand a seed, so it cannot run the Section 8 check either and rejects any
4005
 * key carrying one, including the "both" shape.
4006
 *
4007
 * @param  [in, out]  key       ML-KEM key object.
4008
 * @param  [in]       input     DER buffer.
4009
 * @param  [in]       inSz      Size of DER buffer in bytes.
4010
 * @param  [in, out]  inOutIdx  On in, index into buffer; on out, index after.
4011
 * @return  0 on success.
4012
 * @return  BAD_FUNC_ARG when a pointer is NULL.
4013
 * @return  ASN_PARSE_E when the DER is invalid, names another parameter set,
4014
 *          carries a seed that is not 64 bytes, or carries a seed and an
4015
 *          expanded key that disagree.
4016
 * @return  MEMORY_E when dynamic memory allocation fails.
4017
 * @return  NOT_COMPILED_IN when a key carrying a seed is decoded in a
4018
 *          WOLFSSL_MLKEM_NO_MAKE_KEY or WOLF_CRYPTO_CB_ONLY_MLKEM build.
4019
 */
4020
int wc_MlKemKey_PrivateKeyDecode(MlKemKey* key, const byte* input, word32 inSz,
4021
    word32* inOutIdx)
4022
0
{
4023
0
    int ret = 0;
4024
0
    int keyType = ANONk;
4025
0
    const byte* seed = NULL;
4026
0
    word32 seedLen = 0;
4027
0
    const byte* privKey = NULL;
4028
0
    word32 privKeyLen = 0;
4029
0
    const byte* pubKey = NULL;
4030
0
    word32 pubKeyLen = 0;
4031
0
#ifndef MLKEM_NO_SEED_EXPAND
4032
0
    int keyExpanded = 0;
4033
0
#endif
4034
4035
0
    if ((key == NULL) || (input == NULL) || (inOutIdx == NULL)) {
4036
0
        ret = BAD_FUNC_ARG;
4037
0
    }
4038
0
    if ((ret == 0) && ((key->flags & MLKEM_FLAG_TYPE_SET) != 0)) {
4039
        /* A parameter set was named at init, so hold the DER to it. */
4040
0
        ret = mlkem_type_to_oid_sum(key->type, &keyType);
4041
0
    }
4042
0
    if (ret == 0) {
4043
        /* RFC 9935 Section 6 gives privateKey three CHOICE shapes: a 64 byte
4044
         * seed under an implicit [0], the expanded key as an OCTET STRING, or
4045
         * a SEQUENCE carrying both. The template decoder reports which. */
4046
0
        ret = DecodeAsymKey_Assign(input, inOutIdx, inSz, &seed, &seedLen,
4047
0
            &privKey, &privKeyLen, &pubKey, &pubKeyLen, &keyType);
4048
0
    }
4049
0
    if ((ret == 0) && ((key->flags & MLKEM_FLAG_TYPE_SET) == 0)) {
4050
0
        ret = mlkem_key_adopt_type(key, keyType);
4051
0
    }
4052
#ifdef MLKEM_NO_SEED_EXPAND
4053
    /* Expanding a seed needs key generation, which this build lacks. That
4054
     * rules out the "both" shape too: without the RFC 9935 Section 8
4055
     * comparison, trusting the expanded half would accept a tampered file. */
4056
    if ((ret == 0) && (seed != NULL)) {
4057
        WOLFSSL_MSG("ML-KEM seed needs key generation, which is not built");
4058
        ret = NOT_COMPILED_IN;
4059
    }
4060
    if (ret == 0) {
4061
        ret = wc_MlKemKey_DecodePrivateKey(key, privKey, privKeyLen);
4062
    }
4063
#else
4064
0
    if ((ret == 0) && (seed != NULL)) {
4065
0
        if (seedLen != WC_ML_KEM_MAKEKEY_RAND_SZ) {
4066
0
            ret = ASN_PARSE_E;
4067
0
        }
4068
0
        else {
4069
            /* Expand with ML-KEM.KeyGen_internal(d,z), FIPS 203 algorithm 16,
4070
             * taking the first 32 octets as d and the rest as z. */
4071
        #ifdef WC_MLKEM_NONBLOCK
4072
            /* A decode runs to completion: abandon what is in flight on the
4073
             * key being replaced and expand the seed blocking. */
4074
            wc_MlKemNonBlock* nb = key->nb;
4075
4076
            mlkemkey_nb_release(key);
4077
            key->nb = NULL;
4078
        #endif
4079
0
            ret = wc_MlKemKey_MakeKeyWithRandom(key, seed, (int)seedLen);
4080
        #ifdef WC_MLKEM_NONBLOCK
4081
            key->nb = nb;
4082
        #endif
4083
0
            if (ret == 0) {
4084
0
                keyExpanded = 1;
4085
0
            }
4086
0
        }
4087
0
    }
4088
0
    if ((ret == 0) && (seed != NULL) && (privKey != NULL)) {
4089
        /* The "both" shape. RFC 9935 Section 8: regenerate the expanded form
4090
         * from the seed and reject the key when the two disagree. */
4091
0
        byte* expanded = NULL;
4092
0
        word32 expandedLen = 0;
4093
4094
0
        ret = wc_MlKemKey_PrivateKeySize(key, &expandedLen);
4095
0
        if ((ret == 0) && (expandedLen != privKeyLen)) {
4096
0
            ret = ASN_PARSE_E;
4097
0
        }
4098
0
        if (ret == 0) {
4099
0
            expanded = (byte*)XMALLOC(expandedLen, key->heap,
4100
0
                DYNAMIC_TYPE_TMP_BUFFER);
4101
0
            if (expanded == NULL) {
4102
0
                ret = MEMORY_E;
4103
0
            }
4104
0
        }
4105
0
        if (ret == 0) {
4106
0
            ret = wc_MlKemKey_EncodePrivateKey(key, expanded, expandedLen);
4107
0
        }
4108
0
        if (ret == 0) {
4109
0
            if (XMEMCMP(expanded, privKey, expandedLen) != 0) {
4110
0
                WOLFSSL_MSG("ML-KEM seed and expandedKey disagree");
4111
0
                ret = ASN_PARSE_E;
4112
0
            }
4113
0
        }
4114
0
        if (expanded != NULL) {
4115
0
            ForceZero(expanded, expandedLen);
4116
0
            XFREE(expanded, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
4117
0
        }
4118
0
    }
4119
0
    if ((ret != 0) && keyExpanded) {
4120
        /* The seed was expanded before it could be checked, so scrub it; a
4121
         * failure must not leave a usable private key behind. Gated on the
4122
         * expansion having run, not on seed != NULL: a wrong-length seed never
4123
         * reaches it, and priv may still be NULL under DYNAMIC_KEYS. */
4124
    #ifdef WOLFSSL_MLKEM_DYNAMIC_KEYS
4125
        if (key->priv != NULL) {
4126
            ForceZero(key->priv, key->privAllocSz);
4127
        }
4128
    #else
4129
0
        ForceZero(key->priv, sizeof(key->priv));
4130
0
    #endif
4131
0
        ForceZero(key->z, WC_ML_KEM_SYM_SZ);
4132
0
        key->flags &= MLKEM_FLAG_TYPE_SET;
4133
0
    }
4134
0
    else if ((ret == 0) && (seed == NULL)) {
4135
0
        ret = wc_MlKemKey_DecodePrivateKey(key, privKey, privKeyLen);
4136
0
    }
4137
0
#endif /* MLKEM_NO_SEED_EXPAND */
4138
4139
0
    return ret;
4140
0
}
4141
#endif /* WC_ENABLE_ASYM_KEY_IMPORT */
4142
4143
#endif /* !WOLFSSL_MLKEM_NO_ASN1 */
4144
4145
#endif /* WOLFSSL_HAVE_MLKEM */