1 /*
2 * This file is part of the openHiTLS project.
3 *
4 * openHiTLS is licensed under the Mulan PSL v2.
5 * You can use this software according to the terms and conditions of the Mulan PSL v2.
6 * You may obtain a copy of Mulan PSL v2 at:
7 *
8 * http://license.coscl.org.cn/MulanPSL2
9 *
10 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
11 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
12 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
13 * See the Mulan PSL v2 for more details.
14 */
15
16 #ifndef CRYPT_ML_KEM_LOCAL_H
17 #define CRYPT_ML_KEM_LOCAL_H
18 #include "crypt_mlkem.h"
19 #include "sal_atomic.h"
20 #include "crypt_local_types.h"
21
22 #define MLKEM_N 256
23 #define MLKEM_N_HALF 128
24 #define MLKEM_CIPHER_LEN 384
25
26 #define MLKEM_SEED_LEN 32
27 #define MLKEM_SHARED_KEY_LEN 32
28 #define MLKEM_PRF_BLOCKSIZE 64
29 #define MLKEM_ENCODE_BLOCKSIZE 32
30
31 // 9 = 8.38 = (((MLKEM_BITS_OF_Q * (MLKEM_N/8) * 2^MLKEM_BITS_OF_Q) / MLKEM_Q) + 64) / 64;
32 // array_B_arbitrary_length = 9 * 64 + 2 = 578
33 #define MLKEM_XOF_OUTPUT_LENGTH 578
34
35 #define MLKEM_Q 3329
36 #define MLKEM_BITS_OF_Q 12
37 #define MLKEM_INVN 3303 // MLKEM_N_HALF * MLKEM_INVN = 1 mod MLKEM_Q
38
39 typedef int32_t (*MlKemHashFunc)(uint32_t id, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen);
40
MlKemAddModQ(int16_t * val)41 static inline void MlKemAddModQ(int16_t *val)
42 {
43 while (*val < 0) {
44 *val += MLKEM_Q;
45 }
46 }
47
48 typedef struct {
49 uint8_t k;
50 uint8_t eta1;
51 uint8_t eta2;
52 uint8_t du;
53 uint8_t dv;
54 uint32_t secBits;
55 uint32_t encapsKeyLen;
56 uint32_t decapsKeyLen;
57 uint32_t cipherLen;
58 uint32_t sharedLen;
59 uint32_t bits;
60 } CRYPT_MlKemInfo;
61
62 struct CryptMlKemCtx {
63 int32_t algId;
64 const CRYPT_MlKemInfo *info;
65 uint8_t *ek;
66 uint32_t ekLen;
67 uint8_t *dk;
68 uint32_t dkLen;
69 BSL_SAL_RefCount references;
70 void *libCtx;
71 };
72
73 void MLKEM_ComputNTT(int16_t *a, const int16_t *psi, uint32_t pruLength);
74 void MLKEM_ComputINTT(int16_t *a, const int16_t *psiInv, uint32_t pruLength);
75 void MLKEM_SamplePolyCBD(int16_t *polyF, uint8_t *buf, uint8_t eta);
76 void MLKEM_MatrixMulAdd(uint8_t k, int16_t *matrix[], int16_t *vectorS[], int16_t *vectorE,
77 int16_t *vectorT, const int16_t *factor);
78
79 int32_t MLKEM_KeyGenInternal(CRYPT_ML_KEM_Ctx *ctx, uint8_t *d, uint8_t *z);
80
81 int32_t MLKEM_EncapsInternal(const CRYPT_ML_KEM_Ctx *ctx, uint8_t *ct, uint32_t *ctLen, uint8_t *sk, uint32_t *skLen,
82 uint8_t *m);
83
84 int32_t MLKEM_DecapsInternal(const CRYPT_ML_KEM_Ctx *ctx, uint8_t *ct, uint32_t ctLen, uint8_t *sk, uint32_t *skLen);
85
86 #endif // ML_KEM_LOCAL_H
87