forked from wolfSSL/wolfssl
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwc_mlkem.c
More file actions
2197 lines (2050 loc) · 63.6 KB
/
wc_mlkem.c
File metadata and controls
2197 lines (2050 loc) · 63.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* wc_mlkem.c
*
* Copyright (C) 2006-2026 wolfSSL Inc.
*
* This file is part of wolfSSL.
*
* wolfSSL is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* wolfSSL is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
*/
/* Implementation based on FIPS 203:
* https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.203.pdf
*
* Original implementation based on NIST 3rd Round submission package.
* See link at:
* https://csrc.nist.gov/Projects/post-quantum-cryptography/
* post-quantum-cryptography-standardization/round-3-submissions
*/
/* Possible Kyber options:
*
* WOLFSSL_MLKEM_MAKEKEY_SMALL_MEM Default: OFF
* Uses less dynamic memory to perform key generation.
* Has a small performance trade-off.
* Only usable with C implementation.
*
* WOLFSSL_MLKEM_ENCAPSULATE_SMALL_MEM Default: OFF
* Uses less dynamic memory to perform encapsulation.
* Affects decapsulation too as encapsulation called.
* Has a small performance trade-off.
* Only usable with C implementation.
*
* WOLFSSL_MLKEM_NO_MAKE_KEY Default: OFF
* Disable the make key or key generation API.
* Reduces the code size.
* Turn on when only doing encapsulation.
*
* WOLFSSL_MLKEM_NO_ENCAPSULATE Default: OFF
* Disable the encapsulation API.
* Reduces the code size.
* Turn on when doing make key/decapsulation.
*
* WOLFSSL_MLKEM_NO_DECAPSULATE Default: OFF
* Disable the decapsulation API.
* Reduces the code size.
* Turn on when only doing encapsulation.
*
* WOLFSSL_MLKEM_CACHE_A Default: OFF
* Stores the matrix A during key generation for use in encapsulation when
* performing decapsulation.
* KyberKey is 8KB larger but decapsulation is significantly faster.
* Turn on when performing make key and decapsualtion with same object.
*/
#include <wolfssl/wolfcrypt/libwolfssl_sources.h>
#ifdef WC_MLKEM_NO_ASM
#undef USE_INTEL_SPEEDUP
#undef WOLFSSL_ARMASM
#undef WOLFSSL_RISCV_ASM
#endif
#include <wolfssl/wolfcrypt/mlkem.h>
#include <wolfssl/wolfcrypt/wc_mlkem.h>
#include <wolfssl/wolfcrypt/hash.h>
#include <wolfssl/wolfcrypt/memory.h>
#ifdef NO_INLINE
#include <wolfssl/wolfcrypt/misc.h>
#else
#define WOLFSSL_MISC_INCLUDED
#include <wolfcrypt/src/misc.c>
#endif
#if defined(USE_INTEL_SPEEDUP) || \
(defined(__aarch64__) && defined(WOLFSSL_ARMASM))
#if defined(WOLFSSL_MLKEM_MAKEKEY_SMALL_MEM) || \
defined(WOLFSSL_MLKEM_ENCAPSULATE_SMALL_MEM)
#error "Can't use small memory with assembly optimized code"
#endif
#endif
#if defined(WOLFSSL_MLKEM_CACHE_A)
#if defined(WOLFSSL_MLKEM_MAKEKEY_SMALL_MEM) || \
defined(WOLFSSL_MLKEM_ENCAPSULATE_SMALL_MEM)
#error "Can't cache A with small memory code"
#endif
#endif
#if defined(WOLFSSL_MLKEM_NO_MAKE_KEY) && \
defined(WOLFSSL_MLKEM_NO_ENCAPSULATE) && \
defined(WOLFSSL_MLKEM_NO_DECAPSULATE)
#error "No ML-KEM operations to be built."
#endif
#ifdef WOLFSSL_WC_MLKEM
#ifdef DEBUG_MLKEM
void print_polys(const char* name, const sword16* a, int d1, int d2);
void print_polys(const char* name, const sword16* a, int d1, int d2)
{
int i;
int j;
int k;
fprintf(stderr, "%s: %d %d\n", name, d1, d2);
for (i = 0; i < d1; i++) {
for (j = 0; j < d2; j++) {
for (k = 0; k < 256; k++) {
fprintf(stderr, "%9d,", a[(i*d2*256) + (j*256) + k]);
if ((k % 8) == 7) fprintf(stderr, "\n");
}
fprintf(stderr, "\n");
}
}
}
#endif
#ifdef DEBUG_MLKEM
void print_data(const char* name, const byte* d, int len);
void print_data(const char* name, const byte* d, int len)
{
int i;
fprintf(stderr, "%s\n", name);
for (i = 0; i < len; i++) {
fprintf(stderr, "0x%02x,", d[i]);
if ((i % 16) == 15) fprintf(stderr, "\n");
}
fprintf(stderr, "\n");
}
#endif
/******************************************************************************/
/* Use SHA3-256 to generate 32-bytes of hash. */
#define MLKEM_HASH_H mlkem_hash256
/* Use SHA3-512 to generate 64-bytes of hash. */
#define MLKEM_HASH_G mlkem_hash512
/* Use SHAKE-256 as a key derivation function (KDF). */
#if defined(USE_INTEL_SPEEDUP) || \
(defined(WOLFSSL_ARMASM) && defined(__aarch64__))
#define MLKEM_KDF mlkem_kdf
#else
#define MLKEM_KDF wc_Shake256Hash
#endif
/******************************************************************************/
/* Declare variable to make compiler not optimize code in mlkem_from_msg(). */
volatile sword16 mlkem_opt_blocker = 0;
/******************************************************************************/
#ifndef WC_NO_CONSTRUCTORS
/**
* Create a new ML-KEM key object.
*
* Allocates and initializes a ML-KEM key object.
*
* @param [in] type Type of key:
* WC_ML_KEM_512, WC_ML_KEM_768, WC_ML_KEM_1024,
* KYBER512, KYBER768, KYBER1024.
* @param [in] heap Dynamic memory hint.
* @param [in] devId Device Id.
* @return Pointer to new MlKemKey object, or NULL on failure.
*/
MlKemKey* wc_MlKemKey_New(int type, void* heap, int devId)
{
int ret;
MlKemKey* key = (MlKemKey*)XMALLOC(sizeof(MlKemKey), heap,
DYNAMIC_TYPE_TMP_BUFFER);
if (key != NULL) {
ret = wc_MlKemKey_Init(key, type, heap, devId);
if (ret != 0) {
XFREE(key, heap, DYNAMIC_TYPE_TMP_BUFFER);
key = NULL;
}
}
return key;
}
/**
* Delete and free a ML-KEM key object.
*
* Frees resources associated with a ML-KEM key object and sets pointer to NULL.
*
* @param [in] key ML-KEM key object to delete.
* @param [in, out] key_p Pointer to key pointer to set to NULL.
* @return 0 on success.
* @return BAD_FUNC_ARG when key is NULL.
*/
int wc_MlKemKey_Delete(MlKemKey* key, MlKemKey** key_p)
{
if (key == NULL)
return BAD_FUNC_ARG;
wc_MlKemKey_Free(key);
XFREE(key, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
if (key_p != NULL)
*key_p = NULL;
return 0;
}
#endif /* !WC_NO_CONSTRUCTORS */
/**
* Initialize the Kyber key.
*
* @param [in] type Type of key:
* WC_ML_KEM_512, WC_ML_KEM_768, WC_ML_KEM_1024,
* KYBER512, KYBER768, KYBER1024.
* @param [out] key Kyber key object to initialize.
* @param [in] heap Dynamic memory hint.
* @param [in] devId Device Id.
* @return 0 on success.
* @return BAD_FUNC_ARG when key is NULL or type is unrecognized.
* @return NOT_COMPILED_IN when key type is not supported.
*/
int wc_MlKemKey_Init(MlKemKey* key, int type, void* heap, int devId)
{
int ret = 0;
/* Validate key. */
if (key == NULL) {
ret = BAD_FUNC_ARG;
}
if (ret == 0) {
/* Validate type. */
switch (type) {
#ifndef WOLFSSL_NO_ML_KEM
case WC_ML_KEM_512:
#ifndef WOLFSSL_WC_ML_KEM_512
/* Code not compiled in for Kyber-512. */
ret = NOT_COMPILED_IN;
#endif
break;
case WC_ML_KEM_768:
#ifndef WOLFSSL_WC_ML_KEM_768
/* Code not compiled in for Kyber-768. */
ret = NOT_COMPILED_IN;
#endif
break;
case WC_ML_KEM_1024:
#ifndef WOLFSSL_WC_ML_KEM_1024
/* Code not compiled in for Kyber-1024. */
ret = NOT_COMPILED_IN;
#endif
break;
#endif
#ifdef WOLFSSL_MLKEM_KYBER
case KYBER512:
#ifndef WOLFSSL_KYBER512
/* Code not compiled in for Kyber-512. */
ret = NOT_COMPILED_IN;
#endif
break;
case KYBER768:
#ifndef WOLFSSL_KYBER768
/* Code not compiled in for Kyber-768. */
ret = NOT_COMPILED_IN;
#endif
break;
case KYBER1024:
#ifndef WOLFSSL_KYBER1024
/* Code not compiled in for Kyber-1024. */
ret = NOT_COMPILED_IN;
#endif
break;
#endif
default:
/* No other values supported. */
ret = BAD_FUNC_ARG;
break;
}
}
if (ret == 0) {
/* Keep type for parameters. */
key->type = type;
/* Cache heap pointer. */
key->heap = heap;
#ifdef WOLF_CRYPTO_CB
/* Cache device id - not used in for this algorithm yet. */
key->devId = devId;
#endif
key->flags = 0;
/* Zero out all data. */
XMEMSET(&key->prf, 0, sizeof(key->prf));
/* Initialize the hash algorithm object. */
ret = mlkem_hash_new(&key->hash, heap, devId);
}
if (ret == 0) {
/* Initialize the PRF algorithm object. */
ret = mlkem_prf_new(&key->prf, heap, devId);
}
if (ret == 0) {
mlkem_init();
}
(void)devId;
return ret;
}
/**
* Free the Kyber key object.
*
* @param [in, out] key Kyber key object to dispose of.
* @return 0 on success.
*/
int wc_MlKemKey_Free(MlKemKey* key)
{
if (key != NULL) {
/* Dispose of PRF object. */
mlkem_prf_free(&key->prf);
/* Dispose of hash object. */
mlkem_hash_free(&key->hash);
/* Ensure all private data is zeroed. */
ForceZero(&key->hash, sizeof(key->hash));
ForceZero(&key->prf, sizeof(key->prf));
ForceZero(key->priv, sizeof(key->priv));
ForceZero(key->z, sizeof(key->z));
}
return 0;
}
/******************************************************************************/
#ifndef WOLFSSL_MLKEM_NO_MAKE_KEY
/**
* Make a Kyber key object using a random number generator.
*
* FIPS 203 - Algorithm 19: ML-KEM.KeyGen()
* Generates an encapsulation key and a corresponding decapsulation key.
* 1: d <- B_32 > d is 32 random bytes
* 2: z <- B_32 > z is 32 random bytes
* 3: if d == NULL or z == NULL then
* 4: return falsum
* > return an error indication if random bit generation failed
* 5: end if
* 6: (ek,dk) <- ML-KEM.KeyGen_Interal(d, z)
* > run internal key generation algorithm
* &: return (ek,dk)
*
* @param [in, out] key Kyber key object.
* @param [in] rng Random number generator.
* @return 0 on success.
* @return BAD_FUNC_ARG when key or rng is NULL.
* @return MEMORY_E when dynamic memory allocation failed.
* @return MEMORY_E when dynamic memory allocation failed.
* @return RNG_FAILURE_E when generating random numbers failed.
* @return DRBG_CONT_FAILURE when random number generator health check fails.
*/
int wc_MlKemKey_MakeKey(MlKemKey* key, WC_RNG* rng)
{
int ret = 0;
unsigned char rand[WC_ML_KEM_MAKEKEY_RAND_SZ];
/* Validate parameters. */
if ((key == NULL) || (rng == NULL)) {
ret = BAD_FUNC_ARG;
}
if (ret == 0) {
/* Generate random to use with PRFs.
* Step 1: d is 32 random bytes
* Step 2: z is 32 random bytes
*/
ret = wc_RNG_GenerateBlock(rng, rand, WC_ML_KEM_SYM_SZ * 2);
/* Step 3: ret is not zero when d == NULL or z == NULL. */
}
if (ret == 0) {
/* Make a key pair from the random.
* Step 6. run internal key generation algorithm
* Step 7. public and private key are stored in key
*/
ret = wc_KyberKey_MakeKeyWithRandom(key, rand, sizeof(rand));
}
/* Ensure seeds are zeroized. */
ForceZero((void*)rand, (word32)sizeof(rand));
/* Step 4: return ret != 0 on falsum or internal key generation failure. */
return ret;
}
/**
* Make a Kyber key object using random data.
*
* FIPS 203 - Algorithm 16: ML-KEM.KeyGen_internal(d,z)
* Uses randomness to generate an encapsulation key and a corresponding
* decapsulation key.
* 1: (ek_PKE,dk_PKE) < K-PKE.KeyGen(d) > run key generation for K-PKE
* ...
*
* FIPS 203 - Algorithm 13: K-PKE.KeyGen(d)
* Uses randomness to generate an encryption key and a corresponding decryption
* key.
* 1: (rho,sigma) <- G(d||k)A
* > expand 32+1 bytes to two pseudorandom 32-byte seeds
* 2: N <- 0
* 3-7: generate matrix A_hat
* 8-11: generate s
* 12-15: generate e
* 16-18: calculate t_hat from A_hat, s and e
* ...
*
* @param [in, out] key Kyber key ovject.
* @param [in] rand Random data.
* @param [in] len Length of random data in bytes.
* @return 0 on success.
* @return BAD_FUNC_ARG when key or rand is NULL.
* @return BUFFER_E when length is not WC_ML_KEM_MAKEKEY_RAND_SZ.
* @return NOT_COMPILED_IN when key type is not supported.
* @return MEMORY_E when dynamic memory allocation failed.
*/
int wc_MlKemKey_MakeKeyWithRandom(MlKemKey* key, const unsigned char* rand,
int len)
{
byte buf[2 * WC_ML_KEM_SYM_SZ + 1];
byte* rho = buf;
byte* sigma = buf + WC_ML_KEM_SYM_SZ;
#ifndef WOLFSSL_NO_MALLOC
sword16* e = NULL;
#else
#ifndef WOLFSSL_MLKEM_MAKEKEY_SMALL_MEM
#ifndef WOLFSSL_MLKEM_CACHE_A
sword16 e[(WC_ML_KEM_MAX_K + 1) * WC_ML_KEM_MAX_K * MLKEM_N];
#else
sword16 e[WC_ML_KEM_MAX_K * MLKEM_N];
#endif
#else
sword16 e[WC_ML_KEM_MAX_K * MLKEM_N];
#endif
#endif
#ifndef WOLFSSL_MLKEM_MAKEKEY_SMALL_MEM
sword16* a = NULL;
#endif
sword16* s = NULL;
sword16* t = NULL;
int ret = 0;
int k = 0;
/* Validate parameters. */
if ((key == NULL) || (rand == NULL)) {
ret = BAD_FUNC_ARG;
}
if ((ret == 0) && (len != WC_ML_KEM_MAKEKEY_RAND_SZ)) {
ret = BUFFER_E;
}
if (ret == 0) {
key->flags = 0;
/* Establish parameters based on key type. */
switch (key->type) {
#ifndef WOLFSSL_NO_ML_KEM
#ifdef WOLFSSL_WC_ML_KEM_512
case WC_ML_KEM_512:
k = WC_ML_KEM_512_K;
break;
#endif
#ifdef WOLFSSL_WC_ML_KEM_768
case WC_ML_KEM_768:
k = WC_ML_KEM_768_K;
break;
#endif
#ifdef WOLFSSL_WC_ML_KEM_1024
case WC_ML_KEM_1024:
k = WC_ML_KEM_1024_K;
break;
#endif
#endif
#ifdef WOLFSSL_MLKEM_KYBER
#ifdef WOLFSSL_KYBER512
case KYBER512:
k = KYBER512_K;
break;
#endif
#ifdef WOLFSSL_KYBER768
case KYBER768:
k = KYBER768_K;
break;
#endif
#ifdef WOLFSSL_KYBER1024
case KYBER1024:
k = KYBER1024_K;
break;
#endif
#endif
default:
/* No other values supported. */
ret = NOT_COMPILED_IN;
break;
}
}
#ifndef WOLFSSL_NO_MALLOC
if (ret == 0) {
/* Allocate dynamic memory for matrix and error vector. */
#ifndef WOLFSSL_MLKEM_MAKEKEY_SMALL_MEM
#ifndef WOLFSSL_MLKEM_CACHE_A
/* e (v) | a (m) */
e = (sword16*)XMALLOC((k + 1) * k * MLKEM_N * sizeof(sword16),
key->heap, DYNAMIC_TYPE_TMP_BUFFER);
#else
/* e (v) */
e = (sword16*)XMALLOC(k * MLKEM_N * sizeof(sword16),
key->heap, DYNAMIC_TYPE_TMP_BUFFER);
#endif
#else
/* e (v) */
e = (sword16*)XMALLOC(k * MLKEM_N * sizeof(sword16),
key->heap, DYNAMIC_TYPE_TMP_BUFFER);
#endif
if (e == NULL) {
ret = MEMORY_E;
}
}
#endif
if (ret == 0) {
const byte* d = rand;
#ifdef WOLFSSL_MLKEM_CACHE_A
a = key->a;
#elif !defined(WOLFSSL_MLKEM_MAKEKEY_SMALL_MEM)
/* Matrix A allocated at end of error vector. */
a = e + (k * MLKEM_N);
#endif
#if defined(WOLFSSL_MLKEM_KYBER) && !defined(WOLFSSL_NO_ML_KEM)
if (key->type & MLKEM_KYBER)
#endif
#ifdef WOLFSSL_MLKEM_KYBER
{
/* Expand 32 bytes of random to 32. */
ret = MLKEM_HASH_G(&key->hash, d, WC_ML_KEM_SYM_SZ, NULL, 0, buf);
}
#endif
#if defined(WOLFSSL_MLKEM_KYBER) && !defined(WOLFSSL_NO_ML_KEM)
else
#endif
#ifndef WOLFSSL_NO_ML_KEM
{
buf[0] = k;
/* Expand 33 bytes of random to 32.
* Alg 13: Step 1: (rho,sigma) <- G(d||k)
*/
ret = MLKEM_HASH_G(&key->hash, d, WC_ML_KEM_SYM_SZ, buf, 1, buf);
}
#endif
}
if (ret == 0) {
const byte* z = rand + WC_ML_KEM_SYM_SZ;
s = key->priv;
t = key->pub;
/* Cache the public seed for use in encapsulation and encoding public
* key. */
XMEMCPY(key->pubSeed, rho, WC_ML_KEM_SYM_SZ);
/* Cache the z value for decapsulation and encoding private key. */
XMEMCPY(key->z, z, sizeof(key->z));
/* Initialize PRF for use in noise generation. */
mlkem_prf_init(&key->prf);
#ifndef WOLFSSL_MLKEM_MAKEKEY_SMALL_MEM
/* Generate noise using PRF.
* Alg 13: Steps 8-15: generate s and e
*/
ret = mlkem_get_noise(&key->prf, k, s, e, NULL, sigma);
}
if (ret == 0) {
/* Generate the matrix A.
* Alg 13: Steps 3-7
*/
ret = mlkem_gen_matrix(&key->prf, a, k, rho, 0);
}
if (ret == 0) {
/* Generate key pair from random data.
* Alg 13: Steps 16-18.
*/
mlkem_keygen(s, t, e, a, k);
#else
/* Generate noise using PRF.
* Alg 13: Steps 8-11: generate s
*/
ret = mlkem_get_noise(&key->prf, k, s, NULL, NULL, sigma);
}
if (ret == 0) {
/* Generate key pair from private vector and seeds.
* Alg 13: Steps 3-7: generate matrix A_hat
* Alg 13: 12-15: generate e
* Alg 13: 16-18: calculate t_hat from A_hat, s and e
*/
ret = mlkem_keygen_seeds(s, t, &key->prf, e, k, rho, sigma);
}
if (ret == 0) {
#endif
/* Private and public key are set/available. */
key->flags |= MLKEM_FLAG_PRIV_SET | MLKEM_FLAG_PUB_SET;
#ifdef WOLFSSL_MLKEM_CACHE_A
key->flags |= MLKEM_FLAG_A_SET;
#endif
}
#ifndef WOLFSSL_NO_MALLOC
/* Free dynamic memory allocated in function. */
if (key != NULL) {
XFREE(e, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
}
#endif
return ret;
}
#endif /* !WOLFSSL_MLKEM_NO_MAKE_KEY */
/******************************************************************************/
/**
* Get the size in bytes of cipher text for key.
*
* @param [in] key Kyber key object.
* @param [out] len Length of cipher text in bytes.
* @return 0 on success.
* @return BAD_FUNC_ARG when key or len is NULL.
* @return NOT_COMPILED_IN when key type is not supported.
*/
int wc_MlKemKey_CipherTextSize(MlKemKey* key, word32* len)
{
int ret = 0;
/* Validate parameters. */
if ((key == NULL) || (len == NULL)) {
ret = BAD_FUNC_ARG;
}
if (ret == 0) {
/* Return in 'len' size of the cipher text for the type of this key. */
switch (key->type) {
#ifndef WOLFSSL_NO_ML_KEM
#ifdef WOLFSSL_WC_ML_KEM_512
case WC_ML_KEM_512:
*len = WC_ML_KEM_512_CIPHER_TEXT_SIZE;
break;
#endif
#ifdef WOLFSSL_WC_ML_KEM_768
case WC_ML_KEM_768:
*len = WC_ML_KEM_768_CIPHER_TEXT_SIZE;
break;
#endif
#ifdef WOLFSSL_WC_ML_KEM_1024
case WC_ML_KEM_1024:
*len = WC_ML_KEM_1024_CIPHER_TEXT_SIZE;
break;
#endif
#endif
#ifdef WOLFSSL_MLKEM_KYBER
#ifdef WOLFSSL_KYBER512
case KYBER512:
*len = KYBER512_CIPHER_TEXT_SIZE;
break;
#endif
#ifdef WOLFSSL_KYBER768
case KYBER768:
*len = KYBER768_CIPHER_TEXT_SIZE;
break;
#endif
#ifdef WOLFSSL_KYBER1024
case KYBER1024:
*len = KYBER1024_CIPHER_TEXT_SIZE;
break;
#endif
#endif
default:
/* No other values supported. */
ret = NOT_COMPILED_IN;
break;
}
}
return ret;
}
/**
* Size of a shared secret in bytes. Always KYBER_SS_SZ.
*
* @param [in] key Kyber key object. Not used.
* @param [out] Size of the shared secret created with a Kyber key.
* @return 0 on success.
* @return 0 to indicate success.
*/
int wc_MlKemKey_SharedSecretSize(MlKemKey* key, word32* len)
{
(void)key;
*len = WC_ML_KEM_SS_SZ;
return 0;
}
#if !defined(WOLFSSL_MLKEM_NO_ENCAPSULATE) || \
!defined(WOLFSSL_MLKEM_NO_DECAPSULATE)
/* Encapsulate data and derive secret.
*
* FIPS 203, Algorithm 14: K-PKE.Encrypt(ek_PKE, m, r)
* Uses the encryption key to encrypt a plaintext message using the randomness
* r.
* 1: N <- 0
* 2: t_hat <- ByteDecode_12(ek_PKE[0:384k])
* > run ByteDecode_12 k times to decode t_hat
* 3: rho <- ek_PKE[384k : 384K + 32]
* > extract 32-byte seed from ek_PKE
* 4-8: generate matrix A_hat
* 9-12: generate y
* 13-16: generate e_1
* 17: generate e_2
* 18-19: calculate u
* 20: mu <- Decompress_1(ByteDecode_1(m))
* 21: calculate v
* 22: c_1 <- ByteEncode_d_u(Compress_d_u(u))
* > run ByteEncode_d_u and Compress_d_u k times
* 23: c_2 <- ByteEncode_d_v(Compress_d_v(v))
* 24: return c <- (c_1||c_2)
*
* @param [in] key Kyber key object.
* @param [in] m Random bytes.
* @param [in] r Seed to feed to PRF when generating y, e1 and e2.
* @param [out] c Calculated cipher text.
* @return 0 on success.
* @return NOT_COMPILED_IN when key type is not supported.
*/
static int mlkemkey_encapsulate(MlKemKey* key, const byte* m, byte* r, byte* c)
{
int ret = 0;
sword16* a = NULL;
#ifndef WOLFSSL_MLKEM_ENCAPSULATE_SMALL_MEM
sword16* mu = NULL;
sword16* e1 = NULL;
sword16* e2 = NULL;
#endif
unsigned int k = 0;
unsigned int compVecSz = 0;
#ifndef WOLFSSL_NO_MALLOC
sword16* y = NULL;
#else
#ifndef WOLFSSL_MLKEM_ENCAPSULATE_SMALL_MEM
sword16 y[((WC_ML_KEM_MAX_K + 3) * WC_ML_KEM_MAX_K + 3) * MLKEM_N];
#else
sword16 y[3 * WC_ML_KEM_MAX_K * MLKEM_N];
#endif
#endif
sword16* u = 0;
sword16* v = 0;
/* Establish parameters based on key type. */
switch (key->type) {
#ifndef WOLFSSL_NO_ML_KEM
#ifdef WOLFSSL_WC_ML_KEM_512
case WC_ML_KEM_512:
k = WC_ML_KEM_512_K;
compVecSz = WC_ML_KEM_512_POLY_VEC_COMPRESSED_SZ;
break;
#endif
#ifdef WOLFSSL_WC_ML_KEM_768
case WC_ML_KEM_768:
k = WC_ML_KEM_768_K;
compVecSz = WC_ML_KEM_768_POLY_VEC_COMPRESSED_SZ;
break;
#endif
#ifdef WOLFSSL_WC_ML_KEM_1024
case WC_ML_KEM_1024:
k = WC_ML_KEM_1024_K;
compVecSz = WC_ML_KEM_1024_POLY_VEC_COMPRESSED_SZ;
break;
#endif
#endif
#ifdef WOLFSSL_MLKEM_KYBER
#ifdef WOLFSSL_KYBER512
case KYBER512:
k = KYBER512_K;
compVecSz = KYBER512_POLY_VEC_COMPRESSED_SZ;
break;
#endif
#ifdef WOLFSSL_KYBER768
case KYBER768:
k = KYBER768_K;
compVecSz = KYBER768_POLY_VEC_COMPRESSED_SZ;
break;
#endif
#ifdef WOLFSSL_KYBER1024
case KYBER1024:
k = KYBER1024_K;
compVecSz = KYBER1024_POLY_VEC_COMPRESSED_SZ;
break;
#endif
#endif
default:
/* No other values supported. */
ret = NOT_COMPILED_IN;
break;
}
#ifndef WOLFSSL_NO_MALLOC
if (ret == 0) {
/* Allocate dynamic memory for all matrices, vectors and polynomials. */
#ifndef WOLFSSL_MLKEM_ENCAPSULATE_SMALL_MEM
y = (sword16*)XMALLOC(((k + 3) * k + 3) * MLKEM_N * sizeof(sword16),
key->heap, DYNAMIC_TYPE_TMP_BUFFER);
#else
y = (sword16*)XMALLOC(3 * k * MLKEM_N * sizeof(sword16), key->heap,
DYNAMIC_TYPE_TMP_BUFFER);
#endif
if (y == NULL) {
ret = MEMORY_E;
}
}
#endif
#ifndef WOLFSSL_MLKEM_ENCAPSULATE_SMALL_MEM
if (ret == 0) {
/* Assign allocated dynamic memory to pointers.
* y (b) | a (m) | mu (p) | e1 (p) | e2 (v) | u (v) | v (p) */
a = y + MLKEM_N * k;
mu = a + MLKEM_N * k * k;
e1 = mu + MLKEM_N;
e2 = e1 + MLKEM_N * k;
/* Convert msg to a polynomial.
* Step 20: mu <- Decompress_1(ByteDecode_1(m)) */
mlkem_from_msg(mu, m);
/* Initialize the PRF for use in the noise generation. */
mlkem_prf_init(&key->prf);
/* Generate noise using PRF.
* Steps 9-17: generate y, e_1, e_2
*/
ret = mlkem_get_noise(&key->prf, k, y, e1, e2, r);
}
#ifdef WOLFSSL_MLKEM_CACHE_A
if ((ret == 0) && ((key->flags & MLKEM_FLAG_A_SET) != 0)) {
unsigned int i;
/* Transpose matrix.
* Steps 4-8: generate matrix A_hat (from original) */
for (i = 0; i < k; i++) {
unsigned int j;
for (j = 0; j < k; j++) {
XMEMCPY(&a[(i * k + j) * MLKEM_N],
&key->a[(j * k + i) * MLKEM_N],
MLKEM_N * 2);
}
}
}
else
#endif /* WOLFSSL_MLKEM_CACHE_A */
if (ret == 0) {
/* Generate the transposed matrix.
* Step 4-8: generate matrix A_hat */
ret = mlkem_gen_matrix(&key->prf, a, k, key->pubSeed, 1);
}
if (ret == 0) {
/* Assign remaining allocated dynamic memory to pointers.
* y (v) | a (m) | mu (p) | e1 (p) | r2 (v) | u (v) | v (p)*/
u = e2 + MLKEM_N;
v = u + MLKEM_N * k;
/* Perform encapsulation maths.
* Steps 18-19, 21: calculate u and v */
mlkem_encapsulate(key->pub, u, v, a, y, e1, e2, mu, k);
}
#else /* WOLFSSL_MLKEM_ENCAPSULATE_SMALL_MEM */
if (ret == 0) {
/* Assign allocated dynamic memory to pointers.
* y (v) | a (v) | u (v) */
a = y + MLKEM_N * k;
/* Initialize the PRF for use in the noise generation. */
mlkem_prf_init(&key->prf);
/* Generate noise using PRF.
* Steps 9-12: generate y */
ret = mlkem_get_noise(&key->prf, k, y, NULL, NULL, r);
}
if (ret == 0) {
/* Assign remaining allocated dynamic memory to pointers.
* y (v) | at (v) | u (v) */
u = a + MLKEM_N * k;
v = a;
/* Perform encapsulation maths.
* Steps 13-17: generate e_1 and e_2
* Steps 18-19, 21: calculate u and v */
ret = mlkem_encapsulate_seeds(key->pub, &key->prf, u, a, y, k, m,
key->pubSeed, r);
}
#endif /* WOLFSSL_MLKEM_ENCAPSULATE_SMALL_MEM */
if (ret == 0) {
byte* c1 = c;
byte* c2 = c + compVecSz;
#if defined(WOLFSSL_KYBER512) || defined(WOLFSSL_WC_ML_KEM_512)
if (k == WC_ML_KEM_512_K) {
/* Step 22: c_1 <- ByteEncode_d_u(Compress_d_u(u)) */
mlkem_vec_compress_10(c1, u, k);
/* Step 23: c_2 <- ByteEncode_d_v(Compress_d_v(v)) */
mlkem_compress_4(c2, v);
/* Step 24: return c <- (c_1||c_2) */
}
#endif
#if defined(WOLFSSL_KYBER768) || defined(WOLFSSL_WC_ML_KEM_768)
if (k == WC_ML_KEM_768_K) {
/* Step 22: c_1 <- ByteEncode_d_u(Compress_d_u(u)) */
mlkem_vec_compress_10(c1, u, k);
/* Step 23: c_2 <- ByteEncode_d_v(Compress_d_v(v)) */
mlkem_compress_4(c2, v);
/* Step 24: return c <- (c_1||c_2) */
}
#endif
#if defined(WOLFSSL_KYBER1024) || defined(WOLFSSL_WC_ML_KEM_1024)
if (k == WC_ML_KEM_1024_K) {
/* Step 22: c_1 <- ByteEncode_d_u(Compress_d_u(u)) */
mlkem_vec_compress_11(c1, u);
/* Step 23: c_2 <- ByteEncode_d_v(Compress_d_v(v)) */
mlkem_compress_5(c2, v);
/* Step 24: return c <- (c_1||c_2) */
}
#endif
}
#ifndef WOLFSSL_NO_MALLOC
/* Dispose of dynamic memory allocated in function. */
XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
#endif
return ret;
}
#endif
#if !defined(WOLFSSL_MLKEM_NO_ENCAPSULATE) || \
!defined(WOLFSSL_MLKEM_NO_DECAPSULATE)
static int wc_mlkemkey_check_h(MlKemKey* key)
{
int ret = 0;
/* If public hash (h) is not stored against key, calculate it
* (fields set explicitly instead of using decode).
* Step 1: ... H(ek)...
*/
if ((key->flags & MLKEM_FLAG_H_SET) == 0) {
#ifndef WOLFSSL_NO_MALLOC
byte* pubKey = NULL;
word32 pubKeyLen;
#else
byte pubKey[WC_ML_KEM_MAX_PUBLIC_KEY_SIZE];
word32 pubKeyLen;
#endif
/* Determine how big an encoded public key will be. */
ret = wc_KyberKey_PublicKeySize(key, &pubKeyLen);
if (ret == 0) {
#ifndef WOLFSSL_NO_MALLOC
/* Allocate dynamic memory for encoded public key. */
pubKey = (byte*)XMALLOC(pubKeyLen, key->heap,
DYNAMIC_TYPE_TMP_BUFFER);
if (pubKey == NULL) {
ret = MEMORY_E;
}
}
if (ret == 0) {
#endif
/* Encode public key - h is hash of encoded public key. */
ret = wc_KyberKey_EncodePublicKey(key, pubKey, pubKeyLen);
}
#ifndef WOLFSSL_NO_MALLOC
/* Dispose of encoded public key. */
XFREE(pubKey, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
#endif
}
if ((ret == 0) && ((key->flags & MLKEM_FLAG_H_SET) == 0)) {
/* Implementation issue if h not cached and flag set. */
ret = BAD_STATE_E;
}
return ret;
}
#endif