Coverage Report

Created: 2026-10-31 07:16

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