Coverage Report

Created: 2026-08-23 06:13

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/wolfssl/wolfcrypt/src/sha3.c
Line
Count
Source
1
/* sha3.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
/*
23
 * SHA-3 Build Options:
24
 *
25
 * Core:
26
 * WOLFSSL_SHA3:             Enable SHA-3 support                  default: off
27
 * WOLFSSL_SHA3_SMALL:       Use smaller SHA-3 implementation      default: off
28
 * WOLFSSL_SHAKE128:         Enable SHAKE128 XOF                   default: off
29
 * WOLFSSL_SHAKE256:         Enable SHAKE256 XOF                   default: off
30
 * SHA3_BY_SPEC:             Use specification Keccak-f order      default: off
31
 * WC_SHA3_NO_ASM:           Disable SHA-3 assembly optimizations  default: off
32
 * WC_SHA3_FAULT_HARDEN:     Harden SHA-3 against fault attacks    default: off
33
 * WC_SHA3_SPLIT64:          Run the Keccak permutation on 32-bit halves of each
34
 *                           64-bit lane so a compiler that lowers 64-bit bitwise
35
 *                           ops to out-of-line helper calls (e.g. cl2000 on TI
36
 *                           C28x) emits native 32-bit ops instead.  Auto-enabled
37
 *                           for little-endian WC_16BIT_CPU; the default
38
 *                           permutation is otherwise unchanged.    default: off
39
 *
40
 * Hardware Acceleration (SHA-3-specific):
41
 * WC_ASYNC_ENABLE_SHA3:     Enable async SHA-3 operations         default: off
42
 * WOLFSSL_ARMASM_CRYPTO_SHA3: ARM crypto SHA-3 instructions       default: off
43
 * STM32_HASH_SHA3:          STM32 hardware SHA-3                  default: off
44
 * PSOC6_HASH_SHA3:          PSoC6 hardware SHA-3                  default: off
45
 */
46
47
#define WC_FIPS_LL_CRYPTO
48
#define _WC_BUILDING_SHA3_C
49
50
#include <wolfssl/wolfcrypt/libwolfssl_sources.h>
51
52
#ifdef WC_SHA3_NO_ASM
53
    #undef USE_INTEL_SPEEDUP
54
    #undef WOLFSSL_ARMASM
55
    #undef WOLFSSL_RISCV_ASM
56
#endif
57
#ifdef WOLFSSL_X86_BUILD
58
    #undef USE_INTEL_SPEEDUP
59
#endif
60
61
#if defined(WOLFSSL_PSOC6_CRYPTO)
62
    #include <wolfssl/wolfcrypt/port/cypress/psoc6_crypto.h>
63
#endif
64
65
#if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_XILINX_CRYPT) && \
66
   !defined(WOLFSSL_AFALG_XILINX_SHA3)
67
68
#if FIPS_VERSION3_GE(2,0,0)
69
    #ifdef USE_WINDOWS_API
70
        #pragma code_seg(".fipsA$n")
71
        #pragma const_seg(".fipsB$n")
72
    #endif
73
#endif
74
75
#include <wolfssl/wolfcrypt/sha3.h>
76
#include <wolfssl/wolfcrypt/hash.h>
77
78
#ifdef WOLF_CRYPTO_CB
79
    #include <wolfssl/wolfcrypt/cryptocb.h>
80
#endif
81
#ifdef NO_INLINE
82
    #include <wolfssl/wolfcrypt/misc.h>
83
#else
84
    #define WOLFSSL_MISC_INCLUDED
85
    #include <wolfcrypt/src/misc.c>
86
#endif
87
88
/* Gates the non-WOLFSSL_SHA3_SMALL software Keccak primitives
89
 * (hash_keccak_r, BlockSha3, InitSha3, Sha3Update, Sha3Final and the
90
 * Load64* helpers). Compiled when:
91
 *  - No HW SHA-3 backend is selected (the original baseline), OR
92
 *  - STM32 HW SHA-3 is selected and SHAKE is enabled - SHAKE on STM32MP13
93
 *    runs in software because the HASH peripheral's SHAKE support is
94
 *    fixed-length and does not match wolfSSL's variable-length / iterative
95
 *    SqueezeBlocks API. SHA-3 still uses the HASH peripheral.
96
 *
97
 * Note: the WOLFSSL_SHA3_SMALL branch earlier in this file defines its
98
 * own hash_keccak_r and BlockSha3 unconditionally inside its #ifdef
99
 * block, so this macro only controls the non-SMALL implementation. */
100
#if (!defined(STM32_HASH_SHA3) && !defined(PSOC6_HASH_SHA3)) || \
101
    (defined(STM32_HASH_SHA3) && \
102
     (defined(WOLFSSL_SHAKE128) || defined(WOLFSSL_SHAKE256)))
103
    #define WC_SHA3_SW_KECCAK
104
#endif
105
106
#if FIPS_VERSION3_GE(6,0,0)
107
    const unsigned int wolfCrypt_FIPS_sha3_ro_sanity[2] =
108
                                                     { 0x1a2b3c4d, 0x00000016 };
109
    int wolfCrypt_FIPS_SHA3_sanity(void)
110
    {
111
        return 0;
112
    }
113
#endif
114
115
116
#if defined(USE_INTEL_SPEEDUP) || (defined(__aarch64__) && \
117
        defined(WOLFSSL_ARMASM))
118
    #include <wolfssl/wolfcrypt/cpuid.h>
119
120
    static cpuid_flags_t cpuid_flags = WC_CPUID_INITIALIZER;
121
#ifdef WC_C_DYNAMIC_FALLBACK
122
    #define SHA3_BLOCK (sha3->sha3_block)
123
    #define SHA3_BLOCK_N (sha3->sha3_block_n)
124
#else
125
    void (*sha3_block)(word64 *s) = NULL;
126
    void (*sha3_block_n)(word64 *s, const byte* data, word32 n,
127
        word64 c) = NULL;
128
    #define SHA3_BLOCK sha3_block
129
    #define SHA3_BLOCK_N sha3_block_n
130
#endif
131
#endif
132
133
#ifdef USE_INTEL_SPEEDUP
134
    /* Block-function selection when USE_INTEL_SPEEDUP: AVX2 on Intel, else
135
     * BMI2, else the C block.  Measured single-instance Keccak-f[1600]
136
     * (Ethereum "Optimizing Keccak"; OpenSSL keccak1600-x86_64.pl): AVX2 is
137
     * ~13-17% faster than BMI2 on Intel Haswell..Skylake, tied on Ice Lake,
138
     * but ~2x SLOWER on AMD Zen, so AVX2 is Intel-only.  (Single-stream
139
     * AVX-512 is vpermt2q-bound and slower than BMI2 everywhere measured, so
140
     * it is not built - see scripts sha3_avx512.rb.)
141
     * Overrides: WOLFSSL_SHA3_AVX2 forces AVX2 on any vendor with it;
142
     *            WOLFSSL_SHA3_NO_AVX2 never uses AVX2. */
143
    /* SHA3_USE_AVX2() is defined in sha3.h - shared with ML-DSA. */
144
145
    /* True when the selected block function uses vector registers and so
146
     * needs the caller to save/restore them.  BMI2 and the C block use only
147
     * general registers. */
148
#ifdef WOLFSSL_SHA3_NO_AVX2
149
    #define SHA3_BLOCK_VREGS(f) 0
150
#else
151
    #define SHA3_BLOCK_VREGS(f) ((f) == sha3_block_avx2)
152
#endif
153
#endif
154
155
#if !defined(WOLFSSL_ARMASM) && !defined(WOLFSSL_RISCV_ASM) && \
156
    !defined(WOLFSSL_PPC64_ASM) && !defined(WOLFSSL_PPC32_ASM)
157
158
#ifdef WOLFSSL_SHA3_SMALL
159
/* Rotate a 64-bit value left.
160
 *
161
 * a  Number to rotate left.
162
 * r  Number od bits to rotate left.
163
 * returns the rotated number.
164
 */
165
#define ROTL64(a, n)    (((a)<<(n))|((a)>>(64-(n))))
166
167
/* An array of values to XOR for block operation. */
168
static const word64 hash_keccak_r[24] =
169
{
170
    0x0000000000000001UL, 0x0000000000008082UL,
171
    0x800000000000808aUL, 0x8000000080008000UL,
172
    0x000000000000808bUL, 0x0000000080000001UL,
173
    0x8000000080008081UL, 0x8000000000008009UL,
174
    0x000000000000008aUL, 0x0000000000000088UL,
175
    0x0000000080008009UL, 0x000000008000000aUL,
176
    0x000000008000808bUL, 0x800000000000008bUL,
177
    0x8000000000008089UL, 0x8000000000008003UL,
178
    0x8000000000008002UL, 0x8000000000000080UL,
179
    0x000000000000800aUL, 0x800000008000000aUL,
180
    0x8000000080008081UL, 0x8000000000008080UL,
181
    0x0000000080000001UL, 0x8000000080008008UL
182
};
183
184
/* Indices used in swap and rotate operation. */
185
#define K_I_0   10
186
#define K_I_1    7
187
#define K_I_2   11
188
#define K_I_3   17
189
#define K_I_4   18
190
#define K_I_5    3
191
#define K_I_6    5
192
#define K_I_7   16
193
#define K_I_8    8
194
#define K_I_9   21
195
#define K_I_10  24
196
#define K_I_11   4
197
#define K_I_12  15
198
#define K_I_13  23
199
#define K_I_14  19
200
#define K_I_15  13
201
#define K_I_16  12
202
#define K_I_17   2
203
#define K_I_18  20
204
#define K_I_19  14
205
#define K_I_20  22
206
#define K_I_21   9
207
#define K_I_22   6
208
#define K_I_23   1
209
210
/* Number of bits to rotate in swap and rotate operation. */
211
#define K_R_0    1
212
#define K_R_1    3
213
#define K_R_2    6
214
#define K_R_3   10
215
#define K_R_4   15
216
#define K_R_5   21
217
#define K_R_6   28
218
#define K_R_7   36
219
#define K_R_8   45
220
#define K_R_9   55
221
#define K_R_10   2
222
#define K_R_11  14
223
#define K_R_12  27
224
#define K_R_13  41
225
#define K_R_14  56
226
#define K_R_15   8
227
#define K_R_16  25
228
#define K_R_17  43
229
#define K_R_18  62
230
#define K_R_19  18
231
#define K_R_20  39
232
#define K_R_21  61
233
#define K_R_22  20
234
#define K_R_23  44
235
236
/* Swap and rotate left operation.
237
 *
238
 * s   The state.
239
 * t1  Temporary value.
240
 * t2  Second temporary value.
241
 * i   The index of the loop.
242
 */
243
#define SWAP_ROTL(s, t1, t2, i)                                         \
244
do {                                                                    \
245
    t2 = s[K_I_##i]; s[K_I_##i] = ROTL64(t1, K_R_##i);                  \
246
}                                                                       \
247
while (0)
248
249
/* Mix the XOR of the column's values into each number by column.
250
 *
251
 * s  The state.
252
 * b  Temporary array of XORed column values.
253
 * x  The index of the column.
254
 * t  Temporary variable.
255
 */
256
#define COL_MIX(s, b, x, t)                                             \
257
do {                                                                    \
258
    for (x = 0; x < 5; x++)                                             \
259
        b[x] = s[x + 0] ^ s[x + 5] ^ s[x + 10] ^ s[x + 15] ^ s[x + 20]; \
260
    for (x = 0; x < 5; x++) {                                           \
261
        t = b[(x + 4) % 5] ^ ROTL64(b[(x + 1) % 5], 1);                 \
262
        s[x +  0] ^= t;                                                 \
263
        s[x +  5] ^= t;                                                 \
264
        s[x + 10] ^= t;                                                 \
265
        s[x + 15] ^= t;                                                 \
266
        s[x + 20] ^= t;                                                 \
267
    }                                                                   \
268
}                                                                       \
269
while (0)
270
271
#ifdef SHA3_BY_SPEC
272
/* Mix the row values.
273
 * BMI1 has ANDN instruction ((~a) & b) - Haswell and above.
274
 *
275
 * s   The state.
276
 * b   Temporary array of XORed row values.
277
 * y   The index of the row to work on.
278
 * x   The index of the column.
279
 * t0  Temporary variable.
280
 * t1  Temporary variable.
281
 */
282
#define ROW_MIX(s, b, y, x, t0, t1)                                     \
283
do {                                                                    \
284
    for (y = 0; y < 5; y++) {                                           \
285
        for (x = 0; x < 5; x++)                                         \
286
            b[x] = s[y * 5 + x];                                        \
287
        for (x = 0; x < 5; x++)                                         \
288
            s[y * 5 + x] = b[x] ^ (~b[(x + 1) % 5] & b[(x + 2) % 5]);   \
289
    }                                                                   \
290
}                                                                       \
291
while (0)
292
#else
293
/* Mix the row values.
294
 * a ^ (~b & c) == a ^ (c & (b ^ c)) == (a ^ b) ^ (b | c)
295
 *
296
 * s   The state.
297
 * b   Temporary array of XORed row values.
298
 * y   The index of the row to work on.
299
 * x   The index of the column.
300
 * t0  Temporary variable.
301
 * t1  Temporary variable.
302
 */
303
#define ROW_MIX(s, b, y, x, t12, t34)                                   \
304
do {                                                                    \
305
    for (y = 0; y < 5; y++) {                                           \
306
        for (x = 0; x < 5; x++)                                         \
307
            b[x] = s[y * 5 + x];                                        \
308
        t12 = (b[1] ^ b[2]); t34 = (b[3] ^ b[4]);                       \
309
        s[y * 5 + 0] = b[0] ^ (b[2] &  t12);                            \
310
        s[y * 5 + 1] =  t12 ^ (b[2] | b[3]);                            \
311
        s[y * 5 + 2] = b[2] ^ (b[4] &  t34);                            \
312
        s[y * 5 + 3] =  t34 ^ (b[4] | b[0]);                            \
313
        s[y * 5 + 4] = b[4] ^ (b[1] & (b[0] ^ b[1]));                   \
314
    }                                                                   \
315
}                                                                       \
316
while (0)
317
#endif /* SHA3_BY_SPEC */
318
319
/* The block operation performed on the state.
320
 *
321
 * s  The state.
322
 */
323
void BlockSha3(word64* s)
324
{
325
    byte i, x, y;
326
    word64 t0, t1;
327
    word64 b[5];
328
329
    for (i = 0; i < 24; i++)
330
    {
331
        COL_MIX(s, b, x, t0);
332
333
        t0 = s[1];
334
        SWAP_ROTL(s, t0, t1,  0);
335
        SWAP_ROTL(s, t1, t0,  1);
336
        SWAP_ROTL(s, t0, t1,  2);
337
        SWAP_ROTL(s, t1, t0,  3);
338
        SWAP_ROTL(s, t0, t1,  4);
339
        SWAP_ROTL(s, t1, t0,  5);
340
        SWAP_ROTL(s, t0, t1,  6);
341
        SWAP_ROTL(s, t1, t0,  7);
342
        SWAP_ROTL(s, t0, t1,  8);
343
        SWAP_ROTL(s, t1, t0,  9);
344
        SWAP_ROTL(s, t0, t1, 10);
345
        SWAP_ROTL(s, t1, t0, 11);
346
        SWAP_ROTL(s, t0, t1, 12);
347
        SWAP_ROTL(s, t1, t0, 13);
348
        SWAP_ROTL(s, t0, t1, 14);
349
        SWAP_ROTL(s, t1, t0, 15);
350
        SWAP_ROTL(s, t0, t1, 16);
351
        SWAP_ROTL(s, t1, t0, 17);
352
        SWAP_ROTL(s, t0, t1, 18);
353
        SWAP_ROTL(s, t1, t0, 19);
354
        SWAP_ROTL(s, t0, t1, 20);
355
        SWAP_ROTL(s, t1, t0, 21);
356
        SWAP_ROTL(s, t0, t1, 22);
357
        SWAP_ROTL(s, t1, t0, 23);
358
359
        ROW_MIX(s, b, y, x, t0, t1);
360
361
        s[0] ^= hash_keccak_r[i];
362
    }
363
}
364
#else
365
/* Rotate a 64-bit value left.
366
 *
367
 * a  Number to rotate left.
368
 * r  Number od bits to rotate left.
369
 * returns the rotated number.
370
 */
371
0
#define ROTL64(a, n)    (((a)<<(n))|((a)>>(64-(n))))
372
373
#ifdef WC_SHA3_SW_KECCAK
374
/* An array of values to XOR for block operation. */
375
static const word64 hash_keccak_r[24] =
376
{
377
    W64LIT(0x0000000000000001), W64LIT(0x0000000000008082),
378
    W64LIT(0x800000000000808a), W64LIT(0x8000000080008000),
379
    W64LIT(0x000000000000808b), W64LIT(0x0000000080000001),
380
    W64LIT(0x8000000080008081), W64LIT(0x8000000000008009),
381
    W64LIT(0x000000000000008a), W64LIT(0x0000000000000088),
382
    W64LIT(0x0000000080008009), W64LIT(0x000000008000000a),
383
    W64LIT(0x000000008000808b), W64LIT(0x800000000000008b),
384
    W64LIT(0x8000000000008089), W64LIT(0x8000000000008003),
385
    W64LIT(0x8000000000008002), W64LIT(0x8000000000000080),
386
    W64LIT(0x000000000000800a), W64LIT(0x800000008000000a),
387
    W64LIT(0x8000000080008081), W64LIT(0x8000000000008080),
388
    W64LIT(0x0000000080000001), W64LIT(0x8000000080008008)
389
};
390
#endif
391
392
/* Indices used in swap and rotate operation. */
393
#define KI_0     6
394
#define KI_1    12
395
#define KI_2    18
396
#define KI_3    24
397
#define KI_4     3
398
#define KI_5     9
399
#define KI_6    10
400
#define KI_7    16
401
#define KI_8    22
402
#define KI_9     1
403
#define KI_10    7
404
#define KI_11   13
405
#define KI_12   19
406
#define KI_13   20
407
#define KI_14    4
408
#define KI_15    5
409
#define KI_16   11
410
#define KI_17   17
411
#define KI_18   23
412
#define KI_19    2
413
#define KI_20    8
414
#define KI_21   14
415
#define KI_22   15
416
#define KI_23   21
417
418
/* Number of bits to rotate in swap and rotate operation. */
419
#define KR_0    44
420
#define KR_1    43
421
#define KR_2    21
422
#define KR_3    14
423
#define KR_4    28
424
#define KR_5    20
425
#define KR_6     3
426
#define KR_7    45
427
#define KR_8    61
428
#define KR_9     1
429
#define KR_10    6
430
#define KR_11   25
431
#define KR_12    8
432
#define KR_13   18
433
#define KR_14   27
434
#define KR_15   36
435
#define KR_16   10
436
#define KR_17   15
437
#define KR_18   56
438
#define KR_19   62
439
#define KR_20   55
440
#define KR_21   39
441
#define KR_22   41
442
#define KR_23    2
443
444
/* Mix the XOR of the column's values into each number by column.
445
 *
446
 * s  The state.
447
 * b  Temporary array of XORed column values.
448
 * x  The index of the column.
449
 * t  Temporary variable.
450
 */
451
0
#define COL_MIX(s, b, x, t)                                                         \
452
0
do {                                                                                \
453
0
    (b)[0] = (s)[0] ^ (s)[5] ^ (s)[10] ^ (s)[15] ^ (s)[20];                         \
454
0
    (b)[1] = (s)[1] ^ (s)[6] ^ (s)[11] ^ (s)[16] ^ (s)[21];                         \
455
0
    (b)[2] = (s)[2] ^ (s)[7] ^ (s)[12] ^ (s)[17] ^ (s)[22];                         \
456
0
    (b)[3] = (s)[3] ^ (s)[8] ^ (s)[13] ^ (s)[18] ^ (s)[23];                         \
457
0
    (b)[4] = (s)[4] ^ (s)[9] ^ (s)[14] ^ (s)[19] ^ (s)[24];                         \
458
0
    (t) = (b)[(0 + 4) % 5] ^ ROTL64((b)[(0 + 1) % 5], 1);                           \
459
0
    (s)[ 0] ^= (t); (s)[ 5] ^= (t); (s)[10] ^= (t); (s)[15] ^= (t); (s)[20] ^= (t); \
460
0
    (t) = (b)[(1 + 4) % 5] ^ ROTL64((b)[(1 + 1) % 5], 1);                           \
461
0
    (s)[ 1] ^= (t); (s)[ 6] ^= (t); (s)[11] ^= (t); (s)[16] ^= (t); (s)[21] ^= (t); \
462
0
    (t) = (b)[(2 + 4) % 5] ^ ROTL64((b)[(2 + 1) % 5], 1);                           \
463
0
    (s)[ 2] ^= (t); (s)[ 7] ^= (t); (s)[12] ^= (t); (s)[17] ^= (t); (s)[22] ^= (t); \
464
0
    (t) = (b)[(3 + 4) % 5] ^ ROTL64((b)[(3 + 1) % 5], 1);                           \
465
0
    (s)[ 3] ^= (t); (s)[ 8] ^= (t); (s)[13] ^= (t); (s)[18] ^= (t); (s)[23] ^= (t); \
466
0
    (t) = (b)[(4 + 4) % 5] ^ ROTL64((b)[(4 + 1) % 5], 1);                           \
467
0
    (s)[ 4] ^= (t); (s)[ 9] ^= (t); (s)[14] ^= (t); (s)[19] ^= (t); (s)[24] ^= (t); \
468
0
}                                                                                   \
469
0
while (0)
470
471
0
#define S(s1, i) ROTL64((s1)[KI_##i], KR_##i)
472
473
#ifdef SHA3_BY_SPEC
474
/* Mix the row values.
475
 * BMI1 has ANDN instruction ((~a) & b) - Haswell and above.
476
 *
477
 * s2  The new state.
478
 * s1  The current state.
479
 * b   Temporary array of XORed row values.
480
 * t0  Temporary variable. (Unused)
481
 * t1  Temporary variable. (Unused)
482
 */
483
#define ROW_MIX(s2, s1, b, t0, t1)                    \
484
do {                                                  \
485
    (b)[0] = (s1)[0];                                 \
486
    (b)[1] = S((s1), 0);                              \
487
    (b)[2] = S((s1), 1);                              \
488
    (b)[3] = S((s1), 2);                              \
489
    (b)[4] = S((s1), 3);                              \
490
    (s2)[0] = (b)[0] ^ (~(b)[1] & (b)[2]);            \
491
    (s2)[1] = (b)[1] ^ (~(b)[2] & (b)[3]);            \
492
    (s2)[2] = (b)[2] ^ (~(b)[3] & (b)[4]);            \
493
    (s2)[3] = (b)[3] ^ (~(b)[4] & (b)[0]);            \
494
    (s2)[4] = (b)[4] ^ (~(b)[0] & (b)[1]);            \
495
    (b)[0] = S((s1), 4);                              \
496
    (b)[1] = S((s1), 5);                              \
497
    (b)[2] = S((s1), 6);                              \
498
    (b)[3] = S((s1), 7);                              \
499
    (b)[4] = S((s1), 8);                              \
500
    (s2)[5] = (b)[0] ^ (~(b)[1] & (b)[2]);            \
501
    (s2)[6] = (b)[1] ^ (~(b)[2] & (b)[3]);            \
502
    (s2)[7] = (b)[2] ^ (~(b)[3] & (b)[4]);            \
503
    (s2)[8] = (b)[3] ^ (~(b)[4] & (b)[0]);            \
504
    (s2)[9] = (b)[4] ^ (~(b)[0] & (b)[1]);            \
505
    (b)[0] = S((s1), 9);                              \
506
    (b)[1] = S((s1), 10);                             \
507
    (b)[2] = S((s1), 11);                             \
508
    (b)[3] = S((s1), 12);                             \
509
    (b)[4] = S((s1), 13);                             \
510
    (s2)[10] = (b)[0] ^ (~(b)[1] & (b)[2]);           \
511
    (s2)[11] = (b)[1] ^ (~(b)[2] & (b)[3]);           \
512
    (s2)[12] = (b)[2] ^ (~(b)[3] & (b)[4]);           \
513
    (s2)[13] = (b)[3] ^ (~(b)[4] & (b)[0]);           \
514
    (s2)[14] = (b)[4] ^ (~(b)[0] & (b)[1]);           \
515
    (b)[0] = S((s1), 14);                             \
516
    (b)[1] = S((s1), 15);                             \
517
    (b)[2] = S((s1), 16);                             \
518
    (b)[3] = S((s1), 17);                             \
519
    (b)[4] = S((s1), 18);                             \
520
    (s2)[15] = (b)[0] ^ (~(b)[1] & (b)[2]);           \
521
    (s2)[16] = (b)[1] ^ (~(b)[2] & (b)[3]);           \
522
    (s2)[17] = (b)[2] ^ (~(b)[3] & (b)[4]);           \
523
    (s2)[18] = (b)[3] ^ (~(b)[4] & (b)[0]);           \
524
    (s2)[19] = (b)[4] ^ (~(b)[0] & (b)[1]);           \
525
    (b)[0] = S((s1), 19);                             \
526
    (b)[1] = S((s1), 20);                             \
527
    (b)[2] = S((s1), 21);                             \
528
    (b)[3] = S((s1), 22);                             \
529
    (b)[4] = S((s1), 23);                             \
530
    (s2)[20] = (b)[0] ^ (~(b)[1] & (b)[2]);           \
531
    (s2)[21] = (b)[1] ^ (~(b)[2] & (b)[3]);           \
532
    (s2)[22] = (b)[2] ^ (~(b)[3] & (b)[4]);           \
533
    (s2)[23] = (b)[3] ^ (~(b)[4] & (b)[0]);           \
534
    (s2)[24] = (b)[4] ^ (~(b)[0] & (b)[1]);           \
535
}                                                     \
536
while (0)
537
#else
538
/* Mix the row values.
539
 * a ^ (~b & c) == a ^ (c & (b ^ c)) == (a ^ b) ^ (b | c)
540
 *
541
 * s2  The new state.
542
 * s1  The current state.
543
 * b   Temporary array of XORed row values.
544
 * t12 Temporary variable.
545
 * t34 Temporary variable.
546
 */
547
0
#define ROW_MIX(s2, s1, b, t12, t34)                      \
548
0
do {                                                      \
549
0
    (b)[0] = (s1)[0];                                     \
550
0
    (b)[1] = S((s1), 0);                                  \
551
0
    (b)[2] = S((s1), 1);                                  \
552
0
    (b)[3] = S((s1), 2);                                  \
553
0
    (b)[4] = S((s1), 3);                                  \
554
0
    (t12) = ((b)[1] ^ (b)[2]); (t34) = ((b)[3] ^ (b)[4]); \
555
0
    (s2)[0] = (b)[0] ^ ((b)[2] &  (t12));                 \
556
0
    (s2)[1] =  (t12) ^ ((b)[2] | (b)[3]);                 \
557
0
    (s2)[2] = (b)[2] ^ ((b)[4] &  (t34));                 \
558
0
    (s2)[3] =  (t34) ^ ((b)[4] | (b)[0]);                 \
559
0
    (s2)[4] = (b)[4] ^ ((b)[1] & ((b)[0] ^ (b)[1]));      \
560
0
    (b)[0] = S((s1), 4);                                  \
561
0
    (b)[1] = S((s1), 5);                                  \
562
0
    (b)[2] = S((s1), 6);                                  \
563
0
    (b)[3] = S((s1), 7);                                  \
564
0
    (b)[4] = S((s1), 8);                                  \
565
0
    (t12) = ((b)[1] ^ (b)[2]); (t34) = ((b)[3] ^ (b)[4]); \
566
0
    (s2)[5] = (b)[0] ^ ((b)[2] &  (t12));                 \
567
0
    (s2)[6] =  (t12) ^ ((b)[2] | (b)[3]);                 \
568
0
    (s2)[7] = (b)[2] ^ ((b)[4] &  (t34));                 \
569
0
    (s2)[8] =  (t34) ^ ((b)[4] | (b)[0]);                 \
570
0
    (s2)[9] = (b)[4] ^ ((b)[1] & ((b)[0] ^ (b)[1]));      \
571
0
    (b)[0] = S((s1), 9);                                  \
572
0
    (b)[1] = S((s1), 10);                                 \
573
0
    (b)[2] = S((s1), 11);                                 \
574
0
    (b)[3] = S((s1), 12);                                 \
575
0
    (b)[4] = S((s1), 13);                                 \
576
0
    (t12) = ((b)[1] ^ (b)[2]); (t34) = ((b)[3] ^ (b)[4]); \
577
0
    (s2)[10] = (b)[0] ^ ((b)[2] &  (t12));                \
578
0
    (s2)[11] =  (t12) ^ ((b)[2] | (b)[3]);                \
579
0
    (s2)[12] = (b)[2] ^ ((b)[4] &  (t34));                \
580
0
    (s2)[13] =  (t34) ^ ((b)[4] | (b)[0]);                \
581
0
    (s2)[14] = (b)[4] ^ ((b)[1] & ((b)[0] ^ (b)[1]));     \
582
0
    (b)[0] = S((s1), 14);                                 \
583
0
    (b)[1] = S((s1), 15);                                 \
584
0
    (b)[2] = S((s1), 16);                                 \
585
0
    (b)[3] = S((s1), 17);                                 \
586
0
    (b)[4] = S((s1), 18);                                 \
587
0
    (t12) = ((b)[1] ^ (b)[2]); (t34) = ((b)[3] ^ (b)[4]); \
588
0
    (s2)[15] = (b)[0] ^ ((b)[2] &  (t12));                \
589
0
    (s2)[16] =  (t12) ^ ((b)[2] | (b)[3]);                \
590
0
    (s2)[17] = (b)[2] ^ ((b)[4] &  (t34));                \
591
0
    (s2)[18] =  (t34) ^ ((b)[4] | (b)[0]);                \
592
0
    (s2)[19] = (b)[4] ^ ((b)[1] & ((b)[0] ^ (b)[1]));     \
593
0
    (b)[0] = S((s1), 19);                                 \
594
0
    (b)[1] = S((s1), 20);                                 \
595
0
    (b)[2] = S((s1), 21);                                 \
596
0
    (b)[3] = S((s1), 22);                                 \
597
0
    (b)[4] = S((s1), 23);                                 \
598
0
    (t12) = ((b)[1] ^ (b)[2]); (t34) = ((b)[3] ^ (b)[4]); \
599
0
    (s2)[20] = (b)[0] ^ ((b)[2] &  (t12));                \
600
0
    (s2)[21] =  (t12) ^ ((b)[2] | (b)[3]);                \
601
0
    (s2)[22] = (b)[2] ^ ((b)[4] &  (t34));                \
602
0
    (s2)[23] =  (t34) ^ ((b)[4] | (b)[0]);                \
603
0
    (s2)[24] = (b)[4] ^ ((b)[1] & ((b)[0] ^ (b)[1]));     \
604
0
}                                                         \
605
0
while (0)
606
#endif /* SHA3_BY_SPEC */
607
608
#ifdef WC_SHA3_SW_KECCAK
609
/* The block operation performed on the state.
610
 *
611
 * s  The state.
612
 */
613
614
/* WC_16BIT_CPU (e.g. TI C28x) lowers every 64-bit ^, | and & to an out-of-line
615
 * runtime-helper call (cl2000: __c28xabi_xorll / _orll / _andll), which
616
 * dominates the Keccak permutation.  Auto-select a BlockSha3 that runs on
617
 * 32-bit halves so the compiler emits native 32-bit ops; external state stays
618
 * word64 s[25].  Auto-enabled only for WOLFSSL_WIDE_BYTE (the hardware-validated
619
 * targets); other little-endian 16-bit ports keep the long-tested generic
620
 * permutation but can opt in by defining WC_SHA3_SPLIT64.  Little-endian word
621
 * layout assumed (lo half first). */
622
#if !defined(WC_SHA3_SPLIT64) && defined(WOLFSSL_WIDE_BYTE) && \
623
    !defined(BIG_ENDIAN_ORDER)
624
    #define WC_SHA3_SPLIT64
625
#endif
626
627
#ifdef WC_SHA3_SPLIT64
628
629
/* Rotate the 64-bit value (sl=low, sh=high) left by compile-time constant r in
630
 * 1..63, r != 32, into (dl, dh).  r is always a Keccak rho offset (never 0 or
631
 * 32; r==32 would need a plain half-swap), so that case never occurs.  The & 31
632
 * keeps the shift count in range in the dead (compile-time-eliminated) branch
633
 * so there is no undefined shift. */
634
#define WC_SHA3_RL(dl, dh, sl, sh, r)                                        \
635
    do {                                                                     \
636
        word32 _l = (sl), _h = (sh);                                         \
637
        if ((r) < 32) {                                                      \
638
            (dl) = (word32)((_l << ((r) & 31)) | (_h >> ((32 - (r)) & 31))); \
639
            (dh) = (word32)((_h << ((r) & 31)) | (_l >> ((32 - (r)) & 31))); \
640
        }                                                                    \
641
        else {                                                               \
642
            (dl) = (word32)((_h << (((r) - 32) & 31)) |                      \
643
                            (_l >> ((64 - (r)) & 31)));                      \
644
            (dh) = (word32)((_l << (((r) - 32) & 31)) |                      \
645
                            (_h >> ((64 - (r)) & 31)));                      \
646
        }                                                                    \
647
    } while (0)
648
649
/* Chi over the rotated row held in bl[0..4]/bh[0..4], writing five output lanes
650
 * at (DL,DH)[k..k+4].  a ^ (~b & c) == (a ^ b) ^ (b | c) per half. */
651
#define WC_SHA3_CHI(DL, DH, k)                                  \
652
    do {                                                        \
653
        word32 al = bl[1] ^ bl[2], ah = bh[1] ^ bh[2];          \
654
        word32 cl = bl[3] ^ bl[4], ch = bh[3] ^ bh[4];          \
655
        (DL)[(k)+0] = bl[0] ^ (bl[2] &  al);                    \
656
        (DH)[(k)+0] = bh[0] ^ (bh[2] &  ah);                    \
657
        (DL)[(k)+1] =  al   ^ (bl[2] | bl[3]);                  \
658
        (DH)[(k)+1] =  ah   ^ (bh[2] | bh[3]);                  \
659
        (DL)[(k)+2] = bl[2] ^ (bl[4] &  cl);                    \
660
        (DH)[(k)+2] = bh[2] ^ (bh[4] &  ch);                    \
661
        (DL)[(k)+3] =  cl   ^ (bl[4] | bl[0]);                  \
662
        (DH)[(k)+3] =  ch   ^ (bh[4] | bh[0]);                  \
663
        (DL)[(k)+4] = bl[4] ^ (bl[1] & (bl[0] ^ bl[1]));        \
664
        (DH)[(k)+4] = bh[4] ^ (bh[1] & (bh[0] ^ bh[1]));        \
665
    } while (0)
666
667
/* Theta: mix the column parities into split state L (low) / H (high). */
668
#define WC_SHA3_THETA(L, H)                                                   \
669
    do {                                                                      \
670
        int c;                                                                \
671
        for (c = 0; c < 5; c++) {                                             \
672
            bl[c] = (L)[c]^(L)[c+5]^(L)[c+10]^(L)[c+15]^(L)[c+20];            \
673
            bh[c] = (H)[c]^(H)[c+5]^(H)[c+10]^(H)[c+15]^(H)[c+20];            \
674
        }                                                                     \
675
        for (c = 0; c < 5; c++) {                                             \
676
            int d = (c + 1) % 5, e = (c + 4) % 5;                             \
677
            word32 xl = bl[e] ^ (word32)((bl[d] << 1) | (bh[d] >> 31));       \
678
            word32 xh = bh[e] ^ (word32)((bh[d] << 1) | (bl[d] >> 31));       \
679
            (L)[c]   ^= xl; (H)[c]   ^= xh; (L)[c+5]  ^= xl; (H)[c+5]  ^= xh; \
680
            (L)[c+10]^= xl; (H)[c+10]^= xh; (L)[c+15] ^= xl; (H)[c+15] ^= xh; \
681
            (L)[c+20]^= xl; (H)[c+20]^= xh;                                   \
682
        }                                                                     \
683
    } while (0)
684
685
/* Rho + pi + chi: rotate/permute split state SL/SH into DL/DH. */
686
#define WC_SHA3_ROWMIX(DL, DH, SL, SH)                            \
687
    do {                                                          \
688
        bl[0] = (SL)[0]; bh[0] = (SH)[0];                         \
689
        WC_SHA3_RL(bl[1],bh[1], (SL)[KI_0], (SH)[KI_0],  KR_0);   \
690
        WC_SHA3_RL(bl[2],bh[2], (SL)[KI_1], (SH)[KI_1],  KR_1);   \
691
        WC_SHA3_RL(bl[3],bh[3], (SL)[KI_2], (SH)[KI_2],  KR_2);   \
692
        WC_SHA3_RL(bl[4],bh[4], (SL)[KI_3], (SH)[KI_3],  KR_3);   \
693
        WC_SHA3_CHI(DL, DH, 0);                                   \
694
        WC_SHA3_RL(bl[0],bh[0], (SL)[KI_4], (SH)[KI_4],  KR_4);   \
695
        WC_SHA3_RL(bl[1],bh[1], (SL)[KI_5], (SH)[KI_5],  KR_5);   \
696
        WC_SHA3_RL(bl[2],bh[2], (SL)[KI_6], (SH)[KI_6],  KR_6);   \
697
        WC_SHA3_RL(bl[3],bh[3], (SL)[KI_7], (SH)[KI_7],  KR_7);   \
698
        WC_SHA3_RL(bl[4],bh[4], (SL)[KI_8], (SH)[KI_8],  KR_8);   \
699
        WC_SHA3_CHI(DL, DH, 5);                                   \
700
        WC_SHA3_RL(bl[0],bh[0], (SL)[KI_9], (SH)[KI_9],  KR_9);   \
701
        WC_SHA3_RL(bl[1],bh[1], (SL)[KI_10],(SH)[KI_10], KR_10);  \
702
        WC_SHA3_RL(bl[2],bh[2], (SL)[KI_11],(SH)[KI_11], KR_11);  \
703
        WC_SHA3_RL(bl[3],bh[3], (SL)[KI_12],(SH)[KI_12], KR_12);  \
704
        WC_SHA3_RL(bl[4],bh[4], (SL)[KI_13],(SH)[KI_13], KR_13);  \
705
        WC_SHA3_CHI(DL, DH, 10);                                  \
706
        WC_SHA3_RL(bl[0],bh[0], (SL)[KI_14],(SH)[KI_14], KR_14);  \
707
        WC_SHA3_RL(bl[1],bh[1], (SL)[KI_15],(SH)[KI_15], KR_15);  \
708
        WC_SHA3_RL(bl[2],bh[2], (SL)[KI_16],(SH)[KI_16], KR_16);  \
709
        WC_SHA3_RL(bl[3],bh[3], (SL)[KI_17],(SH)[KI_17], KR_17);  \
710
        WC_SHA3_RL(bl[4],bh[4], (SL)[KI_18],(SH)[KI_18], KR_18);  \
711
        WC_SHA3_CHI(DL, DH, 15);                                  \
712
        WC_SHA3_RL(bl[0],bh[0], (SL)[KI_19],(SH)[KI_19], KR_19);  \
713
        WC_SHA3_RL(bl[1],bh[1], (SL)[KI_20],(SH)[KI_20], KR_20);  \
714
        WC_SHA3_RL(bl[2],bh[2], (SL)[KI_21],(SH)[KI_21], KR_21);  \
715
        WC_SHA3_RL(bl[3],bh[3], (SL)[KI_22],(SH)[KI_22], KR_22);  \
716
        WC_SHA3_RL(bl[4],bh[4], (SL)[KI_23],(SH)[KI_23], KR_23);  \
717
        WC_SHA3_CHI(DL, DH, 20);                                  \
718
    } while (0)
719
720
void BlockSha3(word64* s)
721
{
722
    /* Process the 25 little-endian lanes as 32-bit halves to avoid 64-bit
723
     * helper calls.  XMEMCPY in/out (aliasing s through word32* is strict-
724
     * aliasing UB); st[2k] is lane k's low half, st[2k+1] the high half.
725
     * Round constants are split with shifts for the same reason. */
726
    word32 st[50];
727
    word32 sl[25], sh[25], nl[25], nh[25], bl[5], bh[5];
728
    word32 i, k;
729
    word64 rc;
730
731
    XMEMCPY(st, s, sizeof(st));
732
    for (k = 0; k < 25; k++) {
733
        sl[k] = st[2 * k];
734
        sh[k] = st[2 * k + 1];
735
    }
736
    for (i = 0; i < 24; i += 2) {
737
        WC_SHA3_THETA(sl, sh);
738
        WC_SHA3_ROWMIX(nl, nh, sl, sh);
739
        rc = hash_keccak_r[i];
740
        nl[0] ^= (word32)rc;          nh[0] ^= (word32)(rc >> 32);
741
        WC_SHA3_THETA(nl, nh);
742
        WC_SHA3_ROWMIX(sl, sh, nl, nh);
743
        rc = hash_keccak_r[i + 1];
744
        sl[0] ^= (word32)rc;          sh[0] ^= (word32)(rc >> 32);
745
    }
746
    for (k = 0; k < 25; k++) {
747
        st[2 * k]     = sl[k];
748
        st[2 * k + 1] = sh[k];
749
    }
750
    XMEMCPY(s, st, sizeof(st));
751
}
752
753
#undef WC_SHA3_RL
754
#undef WC_SHA3_CHI
755
#undef WC_SHA3_THETA
756
#undef WC_SHA3_ROWMIX
757
758
#else /* !WC_SHA3_SPLIT64 */
759
760
void BlockSha3(word64* s)
761
0
{
762
0
    word64 n[25];
763
0
    word64 b[5];
764
0
    word64 t0;
765
0
#ifndef SHA3_BY_SPEC
766
0
    word64 t1;
767
0
#endif
768
0
    word32 i;
769
770
0
    for (i = 0; i < 24; i += 2)
771
0
    {
772
0
        COL_MIX(s, b, x, t0);
773
0
        ROW_MIX(n, s, b, t0, t1);
774
0
        n[0] ^= hash_keccak_r[i];
775
776
0
        COL_MIX(n, b, x, t0);
777
0
        ROW_MIX(s, n, b, t0, t1);
778
0
        s[0] ^= hash_keccak_r[i+1];
779
0
    }
780
0
}
781
782
#endif /* WC_SHA3_SPLIT64 */
783
#endif /* WC_SHA3_SW_KECCAK */
784
#endif /* !WOLFSSL_SHA3_SMALL */
785
#endif /* !WOLFSSL_ARMASM && !WOLFSSL_RISCV_ASM && !WOLFSSL_PPC64_ASM &&
786
        * !WOLFSSL_PPC32_ASM */
787
788
#if defined(WOLFSSL_PPC64_ASM)
789
#if defined(WOLFSSL_PPC64_ASM_POWER8)
790
/* PowerPC64 provides two Keccak-f[1600] implementations: the scalar
791
 * BlockSha3_base and a POWER8 (PowerISA 2.07) VSX BlockSha3_power8 (which uses
792
 * vrld/mtvsrd).  Select the POWER8 one at run time when the CPU is POWER8 or
793
 * later.
794
 *
795
 * A run-time flag with direct calls is used rather than a function pointer: an
796
 * indirect call would require an ELFv1 function descriptor, whereas direct
797
 * calls work under both the ELFv1 and ELFv2 ABIs. */
798
#include <wolfssl/wolfcrypt/cpuid.h>
799
800
/* -1 = not yet determined, 0 = base, 1 = POWER8 */
801
static int sha3_use_power8 = -1;
802
803
void BlockSha3(word64* s)
804
{
805
    if (sha3_use_power8 < 0) {
806
        word32 f = cpuid_get_flags();
807
        /* The VSX permutation is only worthwhile where the scalar issue width
808
         * does not already win.  POWER9 (PowerISA 3.0 but not 3.1) has enough
809
         * scalar throughput that BlockSha3_base is faster, so use the VSX path
810
         * only on POWER8 and on POWER10 (3.1) or later. */
811
        sha3_use_power8 = IS_PPC64_ARCH_2_07(f) &&
812
            (!IS_PPC64_ARCH_3_00(f) || IS_PPC64_ARCH_3_1(f));
813
    }
814
815
    if (sha3_use_power8)
816
        BlockSha3_power8(s);
817
    else
818
        BlockSha3_base(s);
819
}
820
#else
821
/* Only the scalar implementation is built; call it directly (no run-time
822
 * dispatch, no function pointer). */
823
void BlockSha3(word64* s)
824
{
825
    BlockSha3_base(s);
826
}
827
#endif
828
#endif
829
/* Scalar PowerPC32 assembly provides BlockSha3 directly (see
830
 * wolfcrypt/src/port/ppc32/ppc32-sha3-asm.S), so nothing is needed here. */
831
832
#ifdef WC_SHA3_SW_KECCAK
833
#if defined(BIG_ENDIAN_ORDER) || defined(WOLFSSL_WIDE_BYTE)
834
static WC_INLINE word64 Load64Unaligned(const unsigned char *a)
835
{
836
    return ((word64)a[0] <<  0) |
837
           ((word64)a[1] <<  8) |
838
           ((word64)a[2] << 16) |
839
           ((word64)a[3] << 24) |
840
           ((word64)a[4] << 32) |
841
           ((word64)a[5] << 40) |
842
           ((word64)a[6] << 48) |
843
           ((word64)a[7] << 56);
844
}
845
846
/* Convert the array of bytes, in little-endian order, to a 64-bit integer.
847
 *
848
 * a  Array of bytes.
849
 * returns a 64-bit integer.
850
 */
851
static word64 Load64BitLittleEndian(const byte* a)
852
{
853
    word64 n = 0;
854
    int i;
855
856
    for (i = 0; i < 8; i++)
857
        n |= (word64)a[i] << (8 * i);
858
859
    return n;
860
}
861
#elif defined(WC_SHA3_FAULT_HARDEN)
862
static WC_INLINE word64 Load64Unaligned(const unsigned char *a) {
863
    return readUnalignedWord64(a);
864
}
865
866
/* Convert the array of bytes, in little-endian order, to a 64-bit integer.
867
 *
868
 * a  Array of bytes.
869
 * returns a 64-bit integer.
870
 */
871
static word64 Load64BitLittleEndian(const byte* a)
872
{
873
    return Load64Unaligned(a);
874
}
875
#endif
876
877
/* Initialize the state for a SHA3-224 hash operation.
878
 *
879
 * sha3   wc_Sha3 object holding state.
880
 * returns 0 on success.
881
 */
882
883
static int InitSha3(wc_Sha3* sha3)
884
0
{
885
0
    int i;
886
887
0
    for (i = 0; i < 25; i++)
888
0
        sha3->s[i] = 0;
889
0
    XMEMSET(sha3->t, 0, sizeof(sha3->t));
890
0
    sha3->i = 0;
891
#ifdef WOLFSSL_HASH_FLAGS
892
    sha3->flags = 0;
893
#endif
894
#ifdef WOLF_CRYPTO_CB
895
    /* Cached hash variant is tied to sponge state; clear it whenever the
896
     * state is reset so reuse for a different SHA3 variant dispatches
897
     * correctly through the crypto callback. */
898
    sha3->hashType = WC_HASH_TYPE_NONE;
899
#endif
900
901
#ifdef USE_INTEL_SPEEDUP
902
    {
903
        int cpuid_flags_were_updated = cpuid_get_flags_ex(&cpuid_flags);
904
#ifdef WC_C_DYNAMIC_FALLBACK
905
        (void)cpuid_flags_were_updated;
906
        if (! CAN_SAVE_VECTOR_REGISTERS()) {
907
            SHA3_BLOCK = BlockSha3;
908
            SHA3_BLOCK_N = NULL;
909
        }
910
        else
911
#else
912
        if ((! cpuid_flags_were_updated) && (SHA3_BLOCK != NULL)) {
913
        }
914
        else
915
#endif
916
        /* See the selection comment above: AVX2 on Intel, otherwise BMI2. */
917
        if (SHA3_USE_AVX2(cpuid_flags)) {
918
            SHA3_BLOCK = sha3_block_avx2;
919
            SHA3_BLOCK_N = sha3_block_n_avx2;
920
        }
921
        else if (IS_INTEL_BMI1(cpuid_flags) && IS_INTEL_BMI2(cpuid_flags)) {
922
            SHA3_BLOCK = sha3_block_bmi2;
923
            SHA3_BLOCK_N = sha3_block_n_bmi2;
924
        }
925
        else {
926
            SHA3_BLOCK = BlockSha3;
927
            SHA3_BLOCK_N = NULL;
928
        }
929
    }
930
#define SHA3_FUNC_PTR
931
#endif /* USE_INTEL_SPEEDUP */
932
#if defined(__aarch64__) && defined(WOLFSSL_ARMASM)
933
    {
934
        int cpuid_flags_were_updated = cpuid_get_flags_ex(&cpuid_flags);
935
        if ((! cpuid_flags_were_updated) && (SHA3_BLOCK != NULL)) {
936
        }
937
        else
938
    #ifdef WOLFSSL_ARMASM_CRYPTO_SHA3
939
        if (IS_AARCH64_SHA3(cpuid_flags)) {
940
            SHA3_BLOCK = BlockSha3_crypto;
941
            SHA3_BLOCK_N = NULL;
942
        }
943
        else
944
    #endif
945
        {
946
            SHA3_BLOCK = BlockSha3_base;
947
            SHA3_BLOCK_N = NULL;
948
        }
949
    }
950
#define SHA3_FUNC_PTR
951
#endif
952
953
0
    return 0;
954
0
}
955
956
#if defined(__aarch64__) && defined(WOLFSSL_ARMASM)
957
void BlockSha3(word64* s)
958
{
959
    (*SHA3_BLOCK)(s);
960
}
961
#endif
962
963
/* Update the SHA-3 hash state with message data.
964
 *
965
 * sha3  wc_Sha3 object holding state.
966
 * data  Message data to be hashed.
967
 * len   Length of the message data.
968
 * p     Number of 64-bit numbers in a block of data to process.
969
 * returns 0 on success.
970
 */
971
static int Sha3Update(wc_Sha3* sha3, const byte* data, word32 len, word32 p)
972
0
{
973
0
    word32 i;
974
0
    word32 blocks;
975
0
    int ret = 0;
976
#ifdef WC_SHA3_FAULT_HARDEN
977
    word32 check = 0;
978
    word32 total_check = 0;
979
#endif
980
#ifdef USE_INTEL_SPEEDUP
981
#ifdef WC_C_DYNAMIC_FALLBACK
982
    void (*sha3_block)(word64 *s) = SHA3_BLOCK;
983
    void (*sha3_block_n)(word64 *s, const byte* data, word32 n,
984
        word64 c) = SHA3_BLOCK_N;
985
#endif
986
#endif /* USE_INTEL_SPEEDUP */
987
988
0
    if ((p < WC_SHA3_512_COUNT) || (p > WC_SHA3_128_COUNT))
989
0
        return BAD_STATE_E;
990
991
#ifdef USE_INTEL_SPEEDUP
992
    if (SHA3_BLOCK_VREGS(sha3_block)) {
993
        ret = SAVE_VECTOR_REGISTERS2();
994
        if (ret != 0) {
995
#ifdef WC_C_DYNAMIC_FALLBACK
996
            sha3_block = BlockSha3;
997
            sha3_block_n = NULL;
998
            ret = 0;
999
#else
1000
            return ret;
1001
#endif
1002
        }
1003
    }
1004
#endif /* USE_INTEL_SPEEDUP */
1005
1006
0
    if (sha3->i > 0) {
1007
0
        byte *t;
1008
0
        word32 l;
1009
0
        if (p * 8 < sha3->i) {
1010
0
            ret = BAD_STATE_E;
1011
0
            goto out;
1012
0
        }
1013
0
        l = (p * 8 - sha3->i);
1014
0
        if (l > len) {
1015
0
            l = len;
1016
0
        }
1017
1018
0
        t = &sha3->t[sha3->i];
1019
0
        for (i = 0; i < l; i++) {
1020
0
            t[i] = data[i];
1021
    #ifdef WC_SHA3_FAULT_HARDEN
1022
            check++;
1023
    #endif
1024
0
        }
1025
    #ifdef WC_SHA3_FAULT_HARDEN
1026
        if (check != l) {
1027
            ret = BAD_COND_E;
1028
            goto out;
1029
        }
1030
        total_check += l;
1031
    #endif
1032
0
        data += i;
1033
0
        len -= i;
1034
0
        sha3->i += i;
1035
1036
0
        if (sha3->i == p * 8) {
1037
0
    #if !defined(BIG_ENDIAN_ORDER) && !defined(WC_SHA3_FAULT_HARDEN) && \
1038
0
        !defined(WOLFSSL_WIDE_BYTE)
1039
0
            xorbuf(sha3->s, sha3->t, (word32)(p * 8));
1040
    #else
1041
            for (i = 0; i < p; i++) {
1042
                sha3->s[i] ^= Load64BitLittleEndian(sha3->t + 8 * i);
1043
            #ifdef WC_SHA3_FAULT_HARDEN
1044
                check++;
1045
            #endif
1046
            }
1047
        #ifdef WC_SHA3_FAULT_HARDEN
1048
            if (check != p + l) {
1049
                ret = BAD_COND_E;
1050
                goto out;
1051
            }
1052
            total_check += p;
1053
        #endif
1054
    #endif
1055
        #ifdef SHA3_FUNC_PTR
1056
            (*sha3_block)(sha3->s);
1057
        #else
1058
0
            BlockSha3(sha3->s);
1059
0
        #endif
1060
0
            sha3->i = 0;
1061
0
        }
1062
0
    }
1063
0
    blocks = len / (p * 8U);
1064
    #ifdef SHA3_FUNC_PTR
1065
    if ((sha3_block_n != NULL) && (blocks > 0)) {
1066
        (*sha3_block_n)(sha3->s, data, blocks, p * 8U);
1067
        len -= blocks * (p * 8U);
1068
        data += blocks * (p * 8U);
1069
        blocks = 0;
1070
    }
1071
    #endif
1072
#ifdef WC_SHA3_FAULT_HARDEN
1073
    total_check += blocks * p;
1074
#endif
1075
0
    for (; blocks > 0; blocks--) {
1076
0
#if !defined(BIG_ENDIAN_ORDER) && !defined(WC_SHA3_FAULT_HARDEN) && \
1077
0
    !defined(WOLFSSL_WIDE_BYTE)
1078
0
        xorbuf(sha3->s, data, (word32)(p * 8));
1079
#else
1080
        for (i = 0; i < p; i++) {
1081
            sha3->s[i] ^= Load64Unaligned(data + 8 * i);
1082
        #ifdef WC_SHA3_FAULT_HARDEN
1083
            check++;
1084
        #endif
1085
        }
1086
    #ifdef WC_SHA3_FAULT_HARDEN
1087
        if (check != total_check - ((blocks - 1) * p)) {
1088
            ret = BAD_COND_E;
1089
            goto out;
1090
        }
1091
    #endif
1092
#endif
1093
    #ifdef SHA3_FUNC_PTR
1094
        (*sha3_block)(sha3->s);
1095
    #else
1096
0
        BlockSha3(sha3->s);
1097
0
    #endif
1098
0
        len -= p * 8U;
1099
0
        data += p * 8U;
1100
0
    }
1101
#ifdef WC_SHA3_FAULT_HARDEN
1102
    if (check != total_check) {
1103
        ret = BAD_COND_E;
1104
        goto out;
1105
    }
1106
#endif
1107
1108
0
out:
1109
1110
#ifdef USE_INTEL_SPEEDUP
1111
    if (SHA3_BLOCK_VREGS(sha3_block)) {
1112
        RESTORE_VECTOR_REGISTERS();
1113
    }
1114
#endif
1115
1116
0
    if (ret == 0) {
1117
0
        if (len > 0) {
1118
0
            XMEMCPY(sha3->t, data, len);
1119
0
        }
1120
0
        sha3->i += len;
1121
0
    }
1122
1123
0
    return ret;
1124
0
}
1125
1126
/* Calculate the SHA-3 hash based on all the message data seen.
1127
 *
1128
 * sha3  wc_Sha3 object holding state.
1129
 * hash  Buffer to hold the hash result.
1130
 * p     Number of 64-bit numbers in a block of data to process.
1131
 * len   Number of bytes in output.
1132
 * returns 0 on success.
1133
 */
1134
#ifdef WOLFSSL_WIDE_BYTE
1135
/* Squeeze len output bytes from the Keccak state, extracting each octet from
1136
 * the 64-bit lanes (little-endian within a lane).  Used where a C 'byte' is
1137
 * wider than 8 bits (CHAR_BIT != 8) so the state cannot be copied as an octet
1138
 * stream. */
1139
static void Sha3SqueezeBytes(byte* out, const word64* s, word32 len)
1140
{
1141
    word32 k;
1142
    for (k = 0; k < len; k++) {
1143
        out[k] = (byte)((s[k >> 3] >> (8 * (k & 7))) & 0xFF);
1144
    }
1145
}
1146
#endif
1147
1148
static int Sha3Final(wc_Sha3* sha3, byte padChar, byte* hash, word32 p, word32 l)
1149
0
{
1150
0
    word32 rate = p * 8U;
1151
0
    word32 j;
1152
#if defined(BIG_ENDIAN_ORDER) || defined(WC_SHA3_FAULT_HARDEN) || \
1153
    defined(WOLFSSL_WIDE_BYTE)
1154
    word32 i;
1155
#endif
1156
#ifdef WC_SHA3_FAULT_HARDEN
1157
    word32 check = 0;
1158
#endif
1159
#if defined(WC_C_DYNAMIC_FALLBACK) && defined(USE_INTEL_SPEEDUP)
1160
    void (*sha3_block)(word64 *s) = SHA3_BLOCK;
1161
#endif
1162
1163
0
    if ((p < WC_SHA3_512_COUNT) || (p > WC_SHA3_128_COUNT))
1164
0
        return BAD_STATE_E;
1165
0
    if (sha3->i >= rate)
1166
0
        return BAD_STATE_E;
1167
1168
0
#if !defined(BIG_ENDIAN_ORDER) && !defined(WC_SHA3_FAULT_HARDEN) && \
1169
0
    !defined(WOLFSSL_WIDE_BYTE)
1170
0
    xorbuf(sha3->s, sha3->t, sha3->i);
1171
#ifdef WOLFSSL_HASH_FLAGS
1172
    if ((p == WC_SHA3_256_COUNT) && (sha3->flags & WC_HASH_SHA3_KECCAK256)) {
1173
        padChar = 0x01;
1174
    }
1175
#endif
1176
0
    ((byte*)sha3->s)[sha3->i ] ^= padChar;
1177
0
    ((byte*)sha3->s)[rate - 1] ^= 0x80;
1178
#else
1179
    sha3->t[rate - 1]  = 0x00;
1180
#ifdef WOLFSSL_HASH_FLAGS
1181
    if ((p == WC_SHA3_256_COUNT) && (sha3->flags & WC_HASH_SHA3_KECCAK256)) {
1182
        padChar = 0x01;
1183
    }
1184
#endif
1185
    sha3->t[sha3->i ]  = padChar;
1186
    sha3->t[rate - 1] |= 0x80;
1187
    if (rate - 1 > sha3->i + 1) {
1188
        XMEMSET(sha3->t + sha3->i + 1, 0, rate - 1U - (sha3->i + 1U));
1189
    }
1190
    for (i = 0; i < p; i++) {
1191
        sha3->s[i] ^= Load64BitLittleEndian(sha3->t + 8 * i);
1192
    #ifdef WC_SHA3_FAULT_HARDEN
1193
        check++;
1194
    #endif
1195
    }
1196
#ifdef WC_SHA3_FAULT_HARDEN
1197
    if (check != p) {
1198
        return BAD_COND_E;
1199
    }
1200
#endif
1201
#endif
1202
1203
#ifdef USE_INTEL_SPEEDUP
1204
    if (SHA3_BLOCK_VREGS(sha3_block)) {
1205
        int ret = SAVE_VECTOR_REGISTERS2();
1206
        if (ret != 0) {
1207
#ifdef WC_C_DYNAMIC_FALLBACK
1208
            sha3_block = BlockSha3;
1209
#else
1210
            return ret;
1211
#endif
1212
        }
1213
    }
1214
#endif
1215
1216
0
    for (j = 0; l - j >= rate; j += rate) {
1217
    #ifdef SHA3_FUNC_PTR
1218
        (*sha3_block)(sha3->s);
1219
    #else
1220
0
        BlockSha3(sha3->s);
1221
0
    #endif
1222
    #if defined(BIG_ENDIAN_ORDER)
1223
        ByteReverseWords64((word64*)(hash + j), sha3->s, rate);
1224
    #elif defined(WOLFSSL_WIDE_BYTE)
1225
        Sha3SqueezeBytes(hash + j, sha3->s, rate);
1226
    #else
1227
0
        XMEMCPY(hash + j, sha3->s, rate);
1228
0
    #endif
1229
0
    }
1230
0
    if (j != l) {
1231
    #ifdef SHA3_FUNC_PTR
1232
        (*sha3_block)(sha3->s);
1233
    #else
1234
0
        BlockSha3(sha3->s);
1235
0
    #endif
1236
    #if defined(BIG_ENDIAN_ORDER)
1237
        ByteReverseWords64(sha3->s, sha3->s, rate);
1238
        XMEMCPY(hash + j, sha3->s, l - j);
1239
    #elif defined(WOLFSSL_WIDE_BYTE)
1240
        Sha3SqueezeBytes(hash + j, sha3->s, l - j);
1241
    #else
1242
0
        XMEMCPY(hash + j, sha3->s, l - j);
1243
0
    #endif
1244
0
    }
1245
#ifdef USE_INTEL_SPEEDUP
1246
    if (SHA3_BLOCK_VREGS(sha3_block)) {
1247
        RESTORE_VECTOR_REGISTERS();
1248
    }
1249
#endif
1250
1251
0
    return 0;
1252
0
}
1253
#endif /* WC_SHA3_SW_KECCAK */
1254
#if defined(STM32_HASH_SHA3)
1255
1256
/* Supports CubeMX HAL or Standard Peripheral Library */
1257
1258
static int wc_InitSha3(wc_Sha3* sha3, void* heap, int devId)
1259
{
1260
    if (sha3 == NULL)
1261
        return BAD_FUNC_ARG;
1262
1263
    (void)devId;
1264
    (void)heap;
1265
1266
    XMEMSET(sha3, 0, sizeof(wc_Sha3));
1267
    wc_Stm32_Hash_Init(&sha3->stmCtx);
1268
    return 0;
1269
}
1270
1271
static int Stm32GetAlgo(word32 p)
1272
{
1273
    switch(p) {
1274
        case WC_SHA3_224_COUNT:
1275
            return HASH_ALGOSELECTION_SHA3_224;
1276
        case WC_SHA3_256_COUNT:
1277
            return HASH_ALGOSELECTION_SHA3_256;
1278
        case WC_SHA3_384_COUNT:
1279
            return HASH_ALGOSELECTION_SHA3_384;
1280
        case WC_SHA3_512_COUNT:
1281
            return HASH_ALGOSELECTION_SHA3_512;
1282
    }
1283
    /* Should never get here */
1284
    return WC_SHA3_224_COUNT;
1285
}
1286
1287
static int wc_Sha3Update(wc_Sha3* sha3, const byte* data, word32 len, word32 p)
1288
{
1289
    int ret = 0;
1290
1291
    if (sha3 == NULL) {
1292
        return BAD_FUNC_ARG;
1293
    }
1294
    if (data == NULL && len == 0) {
1295
        /* valid, but do nothing */
1296
        return 0;
1297
    }
1298
    if (data == NULL) {
1299
        return BAD_FUNC_ARG;
1300
    }
1301
1302
    ret = wolfSSL_CryptHwMutexLock();
1303
    if (ret == 0) {
1304
        ret = wc_Stm32_Hash_Update(&sha3->stmCtx, Stm32GetAlgo(p), data, len,
1305
            p * 8);
1306
        wolfSSL_CryptHwMutexUnLock();
1307
    }
1308
    return ret;
1309
}
1310
1311
static int wc_Sha3Final(wc_Sha3* sha3, byte* hash, word32 p, word32 len)
1312
{
1313
    int ret = 0;
1314
1315
    if (sha3 == NULL || hash == NULL) {
1316
        return BAD_FUNC_ARG;
1317
    }
1318
1319
    ret = wolfSSL_CryptHwMutexLock();
1320
    if (ret == 0) {
1321
        ret = wc_Stm32_Hash_Final(&sha3->stmCtx, Stm32GetAlgo(p), hash, len);
1322
        wolfSSL_CryptHwMutexUnLock();
1323
    }
1324
1325
    (void)wc_InitSha3(sha3, NULL, 0); /* reset state */
1326
1327
    return ret;
1328
}
1329
#elif defined(PSOC6_HASH_SHA3)
1330
1331
static int wc_InitSha3(wc_Sha3* sha3, void* heap, int devId)
1332
{
1333
    int ret;
1334
    if (sha3 == NULL) {
1335
        return BAD_FUNC_ARG;
1336
    }
1337
    (void)devId;
1338
    (void)heap;
1339
1340
    /* Lock the mutex to perform crypto operations */
1341
    ret = wolfSSL_CryptHwMutexLock();
1342
    if (ret == 0) {
1343
        /* Initialize hash state for SHA-3 operation */
1344
        ret = wc_Psoc6_Sha3_Init(sha3);
1345
        /* Release the lock */
1346
        wolfSSL_CryptHwMutexUnLock();
1347
    }
1348
1349
    return ret;
1350
}
1351
1352
static int wc_Sha3Update(wc_Sha3* sha3, const byte* data, word32 len, word32 p)
1353
{
1354
    int ret;
1355
1356
    if (sha3 == NULL || (data == NULL && len > 0)) {
1357
        return BAD_FUNC_ARG;
1358
    }
1359
1360
    if (data == NULL) {
1361
        /* len is 0 here: valid, but do nothing */
1362
        return 0;
1363
    }
1364
1365
    /* Lock the mutex to perform crypto operations */
1366
    ret = wolfSSL_CryptHwMutexLock();
1367
    if (ret == 0) {
1368
        /* Perform SHA3 on the input data and update the hash state */
1369
        ret = wc_Psoc6_Sha3_Update(sha3, data, len, p);
1370
        /* Release the lock */
1371
        wolfSSL_CryptHwMutexUnLock();
1372
    }
1373
1374
    return ret;
1375
}
1376
1377
static int wc_Sha3Final(wc_Sha3* sha3, byte* hash, word32 p, word32 len)
1378
{
1379
    int ret;
1380
1381
    if (sha3 == NULL || hash == NULL) {
1382
        return BAD_FUNC_ARG;
1383
    }
1384
1385
    /* Lock the mutex to perform crypto operations */
1386
    ret = wolfSSL_CryptHwMutexLock();
1387
    if (ret == 0) {
1388
        /* Finalize SHA3 operations and produce digest */
1389
        ret = wc_Psoc6_Sha3_Final(sha3, 0x06, hash, p, len);
1390
        if (ret == 0) {
1391
            /* Initialize hash state for SHA-3 operation */
1392
            ret = wc_Psoc6_Sha3_Init(sha3);
1393
        }
1394
        /* Release the lock */
1395
        wolfSSL_CryptHwMutexUnLock();
1396
    }
1397
1398
    return ret;
1399
}
1400
1401
#else
1402
1403
/* Initialize the state for a SHA-3 hash operation.
1404
 *
1405
 * sha3   wc_Sha3 object holding state.
1406
 * heap   Heap reference for dynamic memory allocation. (Used in async ops.)
1407
 * devId  Device identifier for asynchronous operation.
1408
 * returns 0 on success.
1409
 */
1410
static int wc_InitSha3(wc_Sha3* sha3, void* heap, int devId)
1411
0
{
1412
0
    int ret = 0;
1413
1414
0
    if (sha3 == NULL)
1415
0
        return BAD_FUNC_ARG;
1416
1417
0
    sha3->heap = heap;
1418
0
    ret = InitSha3(sha3);
1419
0
    if (ret != 0)
1420
0
        return ret;
1421
1422
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_SHA3)
1423
    ret = wolfAsync_DevCtxInit(&sha3->asyncDev,
1424
                        WOLFSSL_ASYNC_MARKER_SHA3, sha3->heap, devId);
1425
#endif
1426
#if defined(WOLF_CRYPTO_CB)
1427
    sha3->devId = devId;
1428
    sha3->devCtx = NULL;
1429
    /* Set to none to determine the hash type later */
1430
    /* in the update/final functions based on the p value */
1431
    sha3->hashType = WC_HASH_TYPE_NONE;
1432
#endif
1433
0
    (void)devId;
1434
1435
0
    return ret;
1436
0
}
1437
1438
#if !(defined(WOLFSSL_NOSHA3_224) && defined(WOLFSSL_NOSHA3_256) && \
1439
      defined(WOLFSSL_NOSHA3_384) && defined(WOLFSSL_NOSHA3_512))
1440
/* Update the SHA-3 hash state with message data.
1441
 *
1442
 * sha3  wc_Sha3 object holding state.
1443
 * data  Message data to be hashed.
1444
 * len   Length of the message data.
1445
 * p     Number of 64-bit numbers in a block of data to process.
1446
 * returns 0 on success.
1447
 */
1448
static int wc_Sha3Update(wc_Sha3* sha3, const byte* data, word32 len, word32 p)
1449
0
{
1450
0
    int ret;
1451
1452
0
    if (sha3 == NULL) {
1453
0
        return BAD_FUNC_ARG;
1454
0
    }
1455
1456
0
    if (data == NULL && len == 0) {
1457
        /* valid, but do nothing */
1458
0
        return 0;
1459
0
    }
1460
1461
0
    if (data == NULL) {
1462
0
        return BAD_FUNC_ARG;
1463
0
    }
1464
1465
#ifdef WOLF_CRYPTO_CB
1466
    #ifndef WOLF_CRYPTO_CB_FIND
1467
    if (sha3->devId != INVALID_DEVID)
1468
    #endif
1469
    {
1470
        /* If the hash type is not set, determine it based on the p value */
1471
        /* We can skip the switch statement if the hash type set already */
1472
        if (sha3->hashType == WC_HASH_TYPE_NONE) {
1473
            switch (p) {
1474
                case WC_SHA3_224_COUNT:
1475
                    sha3->hashType = WC_HASH_TYPE_SHA3_224; break;
1476
                case WC_SHA3_256_COUNT:
1477
                    sha3->hashType = WC_HASH_TYPE_SHA3_256; break;
1478
                case WC_SHA3_384_COUNT:
1479
                    sha3->hashType = WC_HASH_TYPE_SHA3_384; break;
1480
                case WC_SHA3_512_COUNT:
1481
                    sha3->hashType = WC_HASH_TYPE_SHA3_512; break;
1482
                default: return BAD_FUNC_ARG;
1483
            }
1484
        }
1485
        ret = wc_CryptoCb_Sha3Hash(sha3, sha3->hashType, data, len, NULL);
1486
        if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE))
1487
            return ret;
1488
        /* fall-through when unavailable */
1489
    }
1490
#endif
1491
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_SHA3)
1492
    if (sha3->asyncDev.marker == WOLFSSL_ASYNC_MARKER_SHA3) {
1493
    #if defined(HAVE_INTEL_QA) && defined(QAT_V2)
1494
        /* QAT only supports SHA3_256 */
1495
        if (p == WC_SHA3_256_COUNT) {
1496
            ret = IntelQaSymSha3(&sha3->asyncDev, NULL, data, len);
1497
            if (ret != WC_NO_ERR_TRACE(NOT_COMPILED_IN))
1498
                return ret;
1499
            /* fall-through when unavailable */
1500
        }
1501
    #endif
1502
    }
1503
#endif /* WOLFSSL_ASYNC_CRYPT */
1504
1505
0
    ret = Sha3Update(sha3, data, len, p);
1506
1507
0
    return ret;
1508
0
}
1509
1510
/* Calculate the SHA-3 hash based on all the message data seen.
1511
 *
1512
 * sha3  wc_Sha3 object holding state.
1513
 * hash  Buffer to hold the hash result.
1514
 * p     Number of 64-bit numbers in a block of data to process.
1515
 * len   Number of bytes in output.
1516
 * returns 0 on success.
1517
 */
1518
static int wc_Sha3Final(wc_Sha3* sha3, byte* hash, word32 p, word32 len)
1519
0
{
1520
0
    int ret;
1521
1522
0
    if (sha3 == NULL || hash == NULL) {
1523
0
        return BAD_FUNC_ARG;
1524
0
    }
1525
1526
#ifdef WOLF_CRYPTO_CB
1527
    #ifndef WOLF_CRYPTO_CB_FIND
1528
    if (sha3->devId != INVALID_DEVID)
1529
    #endif
1530
    {
1531
        /* If the hash type is not set, determine it based on the p value */
1532
        /* We can skip the switch statement if the hash type is set already */
1533
        if (sha3->hashType == WC_HASH_TYPE_NONE) {
1534
            switch (p) {
1535
                case WC_SHA3_224_COUNT:
1536
                    sha3->hashType = WC_HASH_TYPE_SHA3_224; break;
1537
                case WC_SHA3_256_COUNT:
1538
                    sha3->hashType = WC_HASH_TYPE_SHA3_256; break;
1539
                case WC_SHA3_384_COUNT:
1540
                    sha3->hashType = WC_HASH_TYPE_SHA3_384; break;
1541
                case WC_SHA3_512_COUNT:
1542
                    sha3->hashType = WC_HASH_TYPE_SHA3_512; break;
1543
                default: return BAD_FUNC_ARG;
1544
            }
1545
        }
1546
        ret = wc_CryptoCb_Sha3Hash(sha3, sha3->hashType, NULL, 0, hash);
1547
        if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE))
1548
            return ret;
1549
        /* fall-through when unavailable */
1550
    }
1551
#endif
1552
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_SHA3)
1553
    if (sha3->asyncDev.marker == WOLFSSL_ASYNC_MARKER_SHA3) {
1554
    #if defined(HAVE_INTEL_QA) && defined(QAT_V2)
1555
        /* QAT only supports SHA3_256 */
1556
        /* QAT SHA-3 only supported on v2 (8970 or later cards) */
1557
        if (len == WC_SHA3_256_DIGEST_SIZE) {
1558
            ret = IntelQaSymSha3(&sha3->asyncDev, hash, NULL, len);
1559
            if (ret != WC_NO_ERR_TRACE(NOT_COMPILED_IN))
1560
                return ret;
1561
            /* fall-through when unavailable */
1562
        }
1563
    #endif
1564
    }
1565
#endif /* WOLFSSL_ASYNC_CRYPT */
1566
1567
0
    ret = Sha3Final(sha3, 0x06, hash, p, (word32)len);
1568
0
    if (ret != 0)
1569
0
        return ret;
1570
1571
0
    return InitSha3(sha3);  /* reset state */
1572
0
}
1573
#endif
1574
#endif
1575
1576
/* Dispose of any dynamically allocated data from the SHA3-384 operation.
1577
 * (Required for async ops.)
1578
 *
1579
 * sha3  wc_Sha3 object holding state.
1580
 * returns 0 on success.
1581
 */
1582
static void wc_Sha3Free(wc_Sha3* sha3)
1583
0
{
1584
#if defined(WOLF_CRYPTO_CB) && defined(WOLF_CRYPTO_CB_FREE)
1585
    int ret = 0;
1586
#endif
1587
1588
0
    (void)sha3;
1589
1590
#if defined(WOLF_CRYPTO_CB) && defined(WOLF_CRYPTO_CB_FREE)
1591
    if (sha3 == NULL)
1592
        return;
1593
1594
    #ifndef WOLF_CRYPTO_CB_FIND
1595
    if (sha3->devId != INVALID_DEVID)
1596
    #endif
1597
    {
1598
        ret = wc_CryptoCb_Free(sha3->devId, WC_ALGO_TYPE_HASH,
1599
                         sha3->hashType, 0, (void*)sha3);
1600
        /* If they want the standard free, they can call it themselves */
1601
        /* via their callback setting devId to INVALID_DEVID */
1602
        /* otherwise assume the callback handled it */
1603
        if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE))
1604
            return;
1605
        /* fall-through when unavailable */
1606
    }
1607
1608
    /* silence compiler warning */
1609
    (void)ret;
1610
1611
#endif /* WOLF_CRYPTO_CB && WOLF_CRYPTO_CB_FREE */
1612
1613
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_SHA3)
1614
    if (sha3 == NULL)
1615
        return;
1616
1617
    wolfAsync_DevCtxFree(&sha3->asyncDev, WOLFSSL_ASYNC_MARKER_SHA3);
1618
#endif /* WOLFSSL_ASYNC_CRYPT */
1619
1620
#if defined(PSOC6_HASH_SHA3)
1621
    wc_Psoc6_Sha_Free();
1622
#endif
1623
0
}
1624
1625
/* Copy the state of the SHA3 operation.
1626
 *
1627
 * src  wc_Sha3 object holding state top copy.
1628
 * dst  wc_Sha3 object to copy into.
1629
 * returns 0 on success.
1630
 */
1631
static int wc_Sha3Copy(wc_Sha3* src, wc_Sha3* dst)
1632
0
{
1633
0
    int ret = 0;
1634
1635
0
    if (src == NULL || dst == NULL)
1636
0
        return BAD_FUNC_ARG;
1637
1638
#if defined(WOLF_CRYPTO_CB) && defined(WOLF_CRYPTO_CB_COPY)
1639
    #ifndef WOLF_CRYPTO_CB_FIND
1640
    if (src->devId != INVALID_DEVID)
1641
    #endif
1642
    {
1643
        /* Cast the source and destination to be void to keep the abstraction */
1644
        ret = wc_CryptoCb_Copy(src->devId, WC_ALGO_TYPE_HASH,
1645
                               src->hashType, (void*)src, (void*)dst);
1646
        if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE))
1647
            return ret;
1648
        /* fall-through when unavailable */
1649
    }
1650
    ret = 0; /* Reset ret to 0 to avoid returning the callback error code */
1651
#endif /* WOLF_CRYPTO_CB && WOLF_CRYPTO_CB_COPY */
1652
1653
    /* Free dst resources before copy to prevent memory leaks (e.g.,
1654
     * hardware contexts). XMEMCPY overwrites dst. */
1655
0
    wc_Sha3Free(dst);
1656
0
    XMEMCPY(dst, src, sizeof(wc_Sha3));
1657
1658
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_SHA3)
1659
    ret = wolfAsync_DevCopy(&src->asyncDev, &dst->asyncDev);
1660
#endif
1661
1662
#if defined(PSOC6_HASH_SHA3)
1663
    /* Re-initialize internal pointers in hash_state that point inside sha_buffers */
1664
    dst->hash_state.hash = (uint8_t*)((cy_stc_crypto_v2_sha3_buffers_t *)&dst->sha_buffers)->hash;
1665
#endif
1666
1667
#ifdef WOLFSSL_HASH_FLAGS
1668
     dst->flags |= WC_HASH_FLAG_ISCOPY;
1669
#endif
1670
1671
0
    return ret;
1672
0
}
1673
1674
#if !(defined(WOLFSSL_NOSHA3_224) && defined(WOLFSSL_NOSHA3_256) && \
1675
      defined(WOLFSSL_NOSHA3_384) && defined(WOLFSSL_NOSHA3_512))
1676
/* Calculate the SHA3-224 hash based on all the message data so far.
1677
 * More message data can be added, after this operation, using the current
1678
 * state.
1679
 *
1680
 * sha3  wc_Sha3 object holding state.
1681
 * hash  Buffer to hold the hash result. Must be at least 28 bytes.
1682
 * p     Number of 64-bit numbers in a block of data to process.
1683
 * len   Number of bytes in output.
1684
 * returns 0 on success.
1685
 */
1686
static int wc_Sha3GetHash(wc_Sha3* sha3, byte* hash, word32 p, word32 len)
1687
0
{
1688
0
    int ret;
1689
0
    WC_DECLARE_VAR(tmpSha3, wc_Sha3, 1, sha3 ? sha3->heap : NULL);
1690
1691
0
    if (sha3 == NULL || hash == NULL)
1692
0
        return BAD_FUNC_ARG;
1693
1694
0
    WC_ALLOC_VAR_EX(tmpSha3, wc_Sha3, 1, sha3->heap, DYNAMIC_TYPE_TMP_BUFFER,
1695
0
                    return MEMORY_E);
1696
1697
0
    XMEMSET(tmpSha3, 0, sizeof(*tmpSha3));
1698
0
    ret = wc_Sha3Copy(sha3, tmpSha3);
1699
0
    if (ret == 0) {
1700
0
        ret = wc_Sha3Final(tmpSha3, hash, p, len);
1701
0
    }
1702
1703
0
    WC_FREE_VAR_EX(tmpSha3, sha3->heap, DYNAMIC_TYPE_TMP_BUFFER);
1704
0
    return ret;
1705
0
}
1706
#endif
1707
1708
#ifndef WOLFSSL_NOSHA3_224
1709
/* Initialize the state for a SHA3-224 hash operation.
1710
 *
1711
 * sha3   wc_Sha3 object holding state.
1712
 * heap   Heap reference for dynamic memory allocation. (Used in async ops.)
1713
 * devId  Device identifier for asynchronous operation.
1714
 * returns 0 on success.
1715
 */
1716
int wc_InitSha3_224(wc_Sha3* sha3, void* heap, int devId)
1717
0
{
1718
0
    return wc_InitSha3(sha3, heap, devId);
1719
0
}
1720
1721
/* Update the SHA3-224 hash state with message data.
1722
 *
1723
 * sha3  wc_Sha3 object holding state.
1724
 * data  Message data to be hashed.
1725
 * len   Length of the message data.
1726
 * returns 0 on success.
1727
 */
1728
int wc_Sha3_224_Update(wc_Sha3* sha3, const byte* data, word32 len)
1729
0
{
1730
0
    return wc_Sha3Update(sha3, data, len, WC_SHA3_224_COUNT);
1731
0
}
1732
1733
/* Calculate the SHA3-224 hash based on all the message data seen.
1734
 * The state is initialized ready for a new message to hash.
1735
 *
1736
 * sha3  wc_Sha3 object holding state.
1737
 * hash  Buffer to hold the hash result. Must be at least 28 bytes.
1738
 * returns 0 on success.
1739
 */
1740
int wc_Sha3_224_Final(wc_Sha3* sha3, byte* hash)
1741
0
{
1742
0
    return wc_Sha3Final(sha3, hash, WC_SHA3_224_COUNT, WC_SHA3_224_DIGEST_SIZE);
1743
0
}
1744
1745
/* Dispose of any dynamically allocated data from the SHA3-224 operation.
1746
 * (Required for async ops.)
1747
 *
1748
 * sha3  wc_Sha3 object holding state.
1749
 * returns 0 on success.
1750
 */
1751
void wc_Sha3_224_Free(wc_Sha3* sha3)
1752
0
{
1753
0
    wc_Sha3Free(sha3);
1754
0
}
1755
1756
/* Calculate the SHA3-224 hash based on all the message data so far.
1757
 * More message data can be added, after this operation, using the current
1758
 * state.
1759
 *
1760
 * sha3  wc_Sha3 object holding state.
1761
 * hash  Buffer to hold the hash result. Must be at least 28 bytes.
1762
 * returns 0 on success.
1763
 */
1764
int wc_Sha3_224_GetHash(wc_Sha3* sha3, byte* hash)
1765
0
{
1766
0
    return wc_Sha3GetHash(sha3, hash, WC_SHA3_224_COUNT, WC_SHA3_224_DIGEST_SIZE);
1767
0
}
1768
1769
/* Copy the state of the SHA3-224 operation.
1770
 *
1771
 * src  wc_Sha3 object holding state top copy.
1772
 * dst  wc_Sha3 object to copy into.
1773
 * returns 0 on success.
1774
 */
1775
int wc_Sha3_224_Copy(wc_Sha3* src, wc_Sha3* dst)
1776
0
{
1777
0
    return wc_Sha3Copy(src, dst);
1778
0
}
1779
#endif
1780
1781
#ifndef WOLFSSL_NOSHA3_256
1782
/* Initialize the state for a SHA3-256 hash operation.
1783
 *
1784
 * sha3   wc_Sha3 object holding state.
1785
 * heap   Heap reference for dynamic memory allocation. (Used in async ops.)
1786
 * devId  Device identifier for asynchronous operation.
1787
 * returns 0 on success.
1788
 */
1789
int wc_InitSha3_256(wc_Sha3* sha3, void* heap, int devId)
1790
0
{
1791
0
    return wc_InitSha3(sha3, heap, devId);
1792
0
}
1793
1794
/* Update the SHA3-256 hash state with message data.
1795
 *
1796
 * sha3  wc_Sha3 object holding state.
1797
 * data  Message data to be hashed.
1798
 * len   Length of the message data.
1799
 * returns 0 on success.
1800
 */
1801
int wc_Sha3_256_Update(wc_Sha3* sha3, const byte* data, word32 len)
1802
0
{
1803
0
    return wc_Sha3Update(sha3, data, len, WC_SHA3_256_COUNT);
1804
0
}
1805
1806
/* Calculate the SHA3-256 hash based on all the message data seen.
1807
 * The state is initialized ready for a new message to hash.
1808
 *
1809
 * sha3  wc_Sha3 object holding state.
1810
 * hash  Buffer to hold the hash result. Must be at least 32 bytes.
1811
 * returns 0 on success.
1812
 */
1813
int wc_Sha3_256_Final(wc_Sha3* sha3, byte* hash)
1814
0
{
1815
0
    return wc_Sha3Final(sha3, hash, WC_SHA3_256_COUNT, WC_SHA3_256_DIGEST_SIZE);
1816
0
}
1817
1818
/* Dispose of any dynamically allocated data from the SHA3-256 operation.
1819
 * (Required for async ops.)
1820
 *
1821
 * sha3  wc_Sha3 object holding state.
1822
 * returns 0 on success.
1823
 */
1824
void wc_Sha3_256_Free(wc_Sha3* sha3)
1825
0
{
1826
0
    wc_Sha3Free(sha3);
1827
0
}
1828
1829
/* Calculate the SHA3-256 hash based on all the message data so far.
1830
 * More message data can be added, after this operation, using the current
1831
 * state.
1832
 *
1833
 * sha3  wc_Sha3 object holding state.
1834
 * hash  Buffer to hold the hash result. Must be at least 32 bytes.
1835
 * returns 0 on success.
1836
 */
1837
int wc_Sha3_256_GetHash(wc_Sha3* sha3, byte* hash)
1838
0
{
1839
0
    return wc_Sha3GetHash(sha3, hash, WC_SHA3_256_COUNT, WC_SHA3_256_DIGEST_SIZE);
1840
0
}
1841
1842
/* Copy the state of the SHA3-256 operation.
1843
 *
1844
 * src  wc_Sha3 object holding state top copy.
1845
 * dst  wc_Sha3 object to copy into.
1846
 * returns 0 on success.
1847
 */
1848
int wc_Sha3_256_Copy(wc_Sha3* src, wc_Sha3* dst)
1849
0
{
1850
0
    return wc_Sha3Copy(src, dst);
1851
0
}
1852
#endif
1853
1854
#ifndef WOLFSSL_NOSHA3_384
1855
/* Initialize the state for a SHA3-384 hash operation.
1856
 *
1857
 * sha3   wc_Sha3 object holding state.
1858
 * heap   Heap reference for dynamic memory allocation. (Used in async ops.)
1859
 * devId  Device identifier for asynchronous operation.
1860
 * returns 0 on success.
1861
 */
1862
int wc_InitSha3_384(wc_Sha3* sha3, void* heap, int devId)
1863
0
{
1864
0
    return wc_InitSha3(sha3, heap, devId);
1865
0
}
1866
1867
/* Update the SHA3-384 hash state with message data.
1868
 *
1869
 * sha3  wc_Sha3 object holding state.
1870
 * data  Message data to be hashed.
1871
 * len   Length of the message data.
1872
 * returns 0 on success.
1873
 */
1874
int wc_Sha3_384_Update(wc_Sha3* sha3, const byte* data, word32 len)
1875
0
{
1876
0
    return wc_Sha3Update(sha3, data, len, WC_SHA3_384_COUNT);
1877
0
}
1878
1879
/* Calculate the SHA3-384 hash based on all the message data seen.
1880
 * The state is initialized ready for a new message to hash.
1881
 *
1882
 * sha3  wc_Sha3 object holding state.
1883
 * hash  Buffer to hold the hash result. Must be at least 48 bytes.
1884
 * returns 0 on success.
1885
 */
1886
int wc_Sha3_384_Final(wc_Sha3* sha3, byte* hash)
1887
0
{
1888
0
    return wc_Sha3Final(sha3, hash, WC_SHA3_384_COUNT, WC_SHA3_384_DIGEST_SIZE);
1889
0
}
1890
1891
/* Dispose of any dynamically allocated data from the SHA3-384 operation.
1892
 * (Required for async ops.)
1893
 *
1894
 * sha3  wc_Sha3 object holding state.
1895
 * returns 0 on success.
1896
 */
1897
void wc_Sha3_384_Free(wc_Sha3* sha3)
1898
0
{
1899
0
    wc_Sha3Free(sha3);
1900
0
}
1901
1902
/* Calculate the SHA3-384 hash based on all the message data so far.
1903
 * More message data can be added, after this operation, using the current
1904
 * state.
1905
 *
1906
 * sha3  wc_Sha3 object holding state.
1907
 * hash  Buffer to hold the hash result. Must be at least 48 bytes.
1908
 * returns 0 on success.
1909
 */
1910
int wc_Sha3_384_GetHash(wc_Sha3* sha3, byte* hash)
1911
0
{
1912
0
    return wc_Sha3GetHash(sha3, hash, WC_SHA3_384_COUNT, WC_SHA3_384_DIGEST_SIZE);
1913
0
}
1914
1915
/* Copy the state of the SHA3-384 operation.
1916
 *
1917
 * src  wc_Sha3 object holding state top copy.
1918
 * dst  wc_Sha3 object to copy into.
1919
 * returns 0 on success.
1920
 */
1921
int wc_Sha3_384_Copy(wc_Sha3* src, wc_Sha3* dst)
1922
0
{
1923
0
    return wc_Sha3Copy(src, dst);
1924
0
}
1925
#endif
1926
1927
#ifndef WOLFSSL_NOSHA3_512
1928
/* Initialize the state for a SHA3-512 hash operation.
1929
 *
1930
 * sha3   wc_Sha3 object holding state.
1931
 * heap   Heap reference for dynamic memory allocation. (Used in async ops.)
1932
 * devId  Device identifier for asynchronous operation.
1933
 * returns 0 on success.
1934
 */
1935
int wc_InitSha3_512(wc_Sha3* sha3, void* heap, int devId)
1936
0
{
1937
0
    return wc_InitSha3(sha3, heap, devId);
1938
0
}
1939
1940
/* Update the SHA3-512 hash state with message data.
1941
 *
1942
 * sha3  wc_Sha3 object holding state.
1943
 * data  Message data to be hashed.
1944
 * len   Length of the message data.
1945
 * returns 0 on success.
1946
 */
1947
int wc_Sha3_512_Update(wc_Sha3* sha3, const byte* data, word32 len)
1948
0
{
1949
0
    return wc_Sha3Update(sha3, data, len, WC_SHA3_512_COUNT);
1950
0
}
1951
1952
/* Calculate the SHA3-512 hash based on all the message data seen.
1953
 * The state is initialized ready for a new message to hash.
1954
 *
1955
 * sha3  wc_Sha3 object holding state.
1956
 * hash  Buffer to hold the hash result. Must be at least 64 bytes.
1957
 * returns 0 on success.
1958
 */
1959
int wc_Sha3_512_Final(wc_Sha3* sha3, byte* hash)
1960
0
{
1961
0
    return wc_Sha3Final(sha3, hash, WC_SHA3_512_COUNT, WC_SHA3_512_DIGEST_SIZE);
1962
0
}
1963
1964
/* Dispose of any dynamically allocated data from the SHA3-512 operation.
1965
 * (Required for async ops.)
1966
 *
1967
 * sha3  wc_Sha3 object holding state.
1968
 * returns 0 on success.
1969
 */
1970
void wc_Sha3_512_Free(wc_Sha3* sha3)
1971
0
{
1972
0
    wc_Sha3Free(sha3);
1973
0
}
1974
1975
/* Calculate the SHA3-512 hash based on all the message data so far.
1976
 * More message data can be added, after this operation, using the current
1977
 * state.
1978
 *
1979
 * sha3  wc_Sha3 object holding state.
1980
 * hash  Buffer to hold the hash result. Must be at least 64 bytes.
1981
 * returns 0 on success.
1982
 */
1983
int wc_Sha3_512_GetHash(wc_Sha3* sha3, byte* hash)
1984
0
{
1985
0
    return wc_Sha3GetHash(sha3, hash, WC_SHA3_512_COUNT, WC_SHA3_512_DIGEST_SIZE);
1986
0
}
1987
1988
/* Copy the state of the SHA3-512 operation.
1989
 *
1990
 * src  wc_Sha3 object holding state top copy.
1991
 * dst  wc_Sha3 object to copy into.
1992
 * returns 0 on success.
1993
 */
1994
int wc_Sha3_512_Copy(wc_Sha3* src, wc_Sha3* dst)
1995
0
{
1996
0
    return wc_Sha3Copy(src, dst);
1997
0
}
1998
#endif
1999
2000
#ifdef WOLFSSL_HASH_FLAGS
2001
int wc_Sha3_SetFlags(wc_Sha3* sha3, word32 flags)
2002
{
2003
    if (sha3) {
2004
        sha3->flags = flags;
2005
    }
2006
    return 0;
2007
}
2008
int wc_Sha3_GetFlags(wc_Sha3* sha3, word32* flags)
2009
{
2010
    if (sha3 && flags) {
2011
        *flags = sha3->flags;
2012
    }
2013
    return 0;
2014
}
2015
#endif
2016
2017
#ifdef WOLFSSL_SHAKE128
2018
/* Initialize the state for a Shake128 hash operation.
2019
 *
2020
 * shake  wc_Shake object holding state.
2021
 * heap   Heap reference for dynamic memory allocation. (Used in async ops.)
2022
 * devId  Device identifier for asynchronous operation.
2023
 * returns 0 on success.
2024
 */
2025
int wc_InitShake128(wc_Shake* shake, void* heap, int devId)
2026
0
{
2027
0
    int ret = wc_InitSha3(shake, heap, devId);
2028
/* The PSoC6 wc_Sha3 variant has no hashType member */
2029
#if defined(WOLF_CRYPTO_CB) && !defined(PSOC6_HASH_SHA3)
2030
    /* SHAKE never hits the SHA3 auto-detect, so set the type here for the
2031
     * Copy/Free callback dispatch. */
2032
    if (ret == 0)
2033
        shake->hashType = WC_HASH_TYPE_SHAKE128;
2034
#endif
2035
0
    return ret;
2036
0
}
2037
2038
#if defined(PSOC6_HASH_SHA3)
2039
2040
int wc_Shake128_Update(wc_Shake* shake, const byte* data, word32 len)
2041
{
2042
    int ret;
2043
    if (shake == NULL || (data == NULL && len > 0)) {
2044
         return BAD_FUNC_ARG;
2045
    }
2046
2047
    if (data == NULL) {
2048
        /* len is 0 here: valid, but do nothing */
2049
        return 0;
2050
    }
2051
2052
    /* Lock the mutex to perform crypto operations */
2053
    ret = wolfSSL_CryptHwMutexLock();
2054
    if (ret == 0) {
2055
        /* Perform SHA3 on the input data and update the hash state */
2056
        ret = wc_Psoc6_Sha3_Update(shake, data, len, WC_SHA3_128_COUNT);
2057
        /* Release the lock */
2058
        wolfSSL_CryptHwMutexUnLock();
2059
    }
2060
2061
    return ret;
2062
}
2063
2064
int wc_Shake128_Final(wc_Shake* shake, byte* hash, word32 hashLen)
2065
{
2066
    int ret;
2067
2068
    if (shake == NULL || hash == NULL) {
2069
        return BAD_FUNC_ARG;
2070
    }
2071
2072
    /* Lock the mutex to perform crypto operations */
2073
    ret = wolfSSL_CryptHwMutexLock();
2074
    if (ret == 0) {
2075
        /* Finalize SHA3 operations and produce digest */
2076
        ret = wc_Psoc6_Sha3_Final(shake, 0x1f, hash, WC_SHA3_128_COUNT, hashLen);
2077
        if (ret == 0) {
2078
            /* Initialize hash state for SHA-3 operation */
2079
            ret = wc_Psoc6_Sha3_Init(shake);
2080
        }
2081
        /* Release the lock */
2082
        wolfSSL_CryptHwMutexUnLock();
2083
    }
2084
2085
    return ret;
2086
2087
}
2088
2089
int wc_Shake128_Absorb(wc_Shake* shake, const byte* data, word32 len)
2090
{
2091
    int ret;
2092
2093
    if ((shake == NULL) || (data == NULL && len != 0)) {
2094
        return BAD_FUNC_ARG;
2095
    }
2096
2097
    /* Lock the mutex to perform crypto operations */
2098
    ret = wolfSSL_CryptHwMutexLock();
2099
    if (ret == 0) {
2100
        /* Perform SHA3 on the input data and update the hash state */
2101
        ret = wc_Psoc6_Sha3_Update(shake, data, len, WC_SHA3_128_COUNT);
2102
        if (ret == 0) {
2103
            /* Finalize SHA3 operations and produce digest */
2104
            ret = wc_Psoc6_Sha3_Final(shake, 0x1f, NULL, WC_SHA3_128_COUNT, 0);
2105
        }
2106
        /* Release the lock */
2107
        wolfSSL_CryptHwMutexUnLock();
2108
    }
2109
2110
    return ret;
2111
}
2112
2113
2114
int wc_Shake128_SqueezeBlocks(wc_Shake* shake, byte* out, word32 blockCnt)
2115
{
2116
    int ret;
2117
    if ((shake == NULL) || (out == NULL && blockCnt != 0)) {
2118
        return BAD_FUNC_ARG;
2119
    }
2120
2121
    /* Lock the mutex to perform crypto operations */
2122
    ret = wolfSSL_CryptHwMutexLock();
2123
    if (ret == 0) {
2124
        /* Squeeze output blocks from current hash state */
2125
        ret = wc_Psoc6_Shake_SqueezeBlocks(shake, out, blockCnt);
2126
        /* Release the lock */
2127
        wolfSSL_CryptHwMutexUnLock();
2128
    }
2129
2130
    return ret;
2131
}
2132
#else
2133
/* Update the SHAKE128 hash state with message data.
2134
 *
2135
 * shake  wc_Shake object holding state.
2136
 * data  Message data to be hashed.
2137
 * len   Length of the message data.
2138
 * returns 0 on success.
2139
 */
2140
int wc_Shake128_Update(wc_Shake* shake, const byte* data, word32 len)
2141
0
{
2142
0
    if (shake == NULL) {
2143
0
        return BAD_FUNC_ARG;
2144
0
    }
2145
2146
0
    if (data == NULL && len == 0) {
2147
        /* valid, but do nothing */
2148
0
        return 0;
2149
0
    }
2150
2151
0
    if (data == NULL) {
2152
0
        return BAD_FUNC_ARG;
2153
0
    }
2154
2155
#ifdef WOLF_CRYPTO_CB
2156
    #ifndef WOLF_CRYPTO_CB_FIND
2157
    if (shake->devId != INVALID_DEVID)
2158
    #endif
2159
    {
2160
        int ret = wc_CryptoCb_Shake(shake, WC_HASH_TYPE_SHAKE128, data, len,
2161
            NULL, 0);
2162
        if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE))
2163
            return ret;
2164
        /* fall-through when unavailable */
2165
    }
2166
#endif
2167
2168
0
    return Sha3Update(shake, data, len, WC_SHA3_128_COUNT);
2169
0
}
2170
2171
/* Calculate the SHAKE128 hash based on all the message data seen.
2172
 * The state is initialized ready for a new message to hash.
2173
 *
2174
 * shake  wc_Shake object holding state.
2175
 * hash  Buffer to hold the hash result. Must be at least 64 bytes.
2176
 * returns 0 on success.
2177
 */
2178
int wc_Shake128_Final(wc_Shake* shake, byte* hash, word32 hashLen)
2179
0
{
2180
0
    int ret;
2181
2182
0
    if (shake == NULL || hash == NULL) {
2183
0
        return BAD_FUNC_ARG;
2184
0
    }
2185
2186
#ifdef WOLF_CRYPTO_CB
2187
    #ifndef WOLF_CRYPTO_CB_FIND
2188
    if (shake->devId != INVALID_DEVID)
2189
    #endif
2190
    {
2191
        ret = wc_CryptoCb_Shake(shake, WC_HASH_TYPE_SHAKE128, NULL, 0, hash,
2192
            hashLen);
2193
        if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE))
2194
            return ret;
2195
        /* fall-through when unavailable */
2196
    }
2197
#endif
2198
2199
0
    ret = Sha3Final(shake, 0x1f, hash, WC_SHA3_128_COUNT, hashLen);
2200
0
    if (ret != 0)
2201
0
        return ret;
2202
2203
0
    ret = InitSha3(shake);  /* reset state */
2204
#ifdef WOLF_CRYPTO_CB
2205
    /* Restore the type cleared by the reset for Copy/Free dispatch. */
2206
    if (ret == 0)
2207
        shake->hashType = WC_HASH_TYPE_SHAKE128;
2208
#endif
2209
0
    return ret;
2210
0
}
2211
2212
/* Absorb the data for squeezing.
2213
 *
2214
 * Update and final with data but no output and no reset
2215
 *
2216
 * shake  wc_Shake object holding state.
2217
 * data  Data to absorb.
2218
 * len  Length of d to absorb in bytes.
2219
 * returns 0 on success.
2220
 */
2221
int wc_Shake128_Absorb(wc_Shake* shake, const byte* data, word32 len)
2222
0
{
2223
0
    int ret;
2224
2225
0
    if ((shake == NULL) || (data == NULL && len != 0)) {
2226
0
        return BAD_FUNC_ARG;
2227
0
    }
2228
2229
0
    ret = Sha3Update(shake, data, len, WC_SHA3_128_COUNT);
2230
0
    if (ret == 0) {
2231
0
        byte hash[1];
2232
0
        ret = Sha3Final(shake, 0x1f, hash, WC_SHA3_128_COUNT, 0);
2233
0
    }
2234
    /* No partial data. */
2235
0
    shake->i = 0;
2236
2237
0
    return ret;
2238
0
}
2239
2240
#ifdef WC_C_DYNAMIC_FALLBACK
2241
    #undef SHA3_BLOCK
2242
    #undef SHA3_BLOCK_N
2243
    #define SHA3_BLOCK (shake->sha3_block)
2244
    #define SHA3_BLOCK_N (shake->sha3_block_n)
2245
#endif
2246
2247
/* Squeeze the state to produce pseudo-random output.
2248
 *
2249
 * shake  wc_Shake object holding state.
2250
 * out  Output buffer.
2251
 * blockCnt  Number of blocks to write.
2252
 * returns 0 on success.
2253
 */
2254
int wc_Shake128_SqueezeBlocks(wc_Shake* shake, byte* out, word32 blockCnt)
2255
0
{
2256
#if defined(WC_C_DYNAMIC_FALLBACK) && defined(USE_INTEL_SPEEDUP)
2257
    void (*sha3_block)(word64 *s);
2258
#endif
2259
2260
0
    if ((shake == NULL) || (out == NULL && blockCnt != 0)) {
2261
0
        return BAD_FUNC_ARG;
2262
0
    }
2263
2264
#ifdef USE_INTEL_SPEEDUP
2265
#ifdef WC_C_DYNAMIC_FALLBACK
2266
    sha3_block = SHA3_BLOCK;
2267
#endif
2268
2269
    if (SHA3_BLOCK_VREGS(sha3_block)) {
2270
        int ret = SAVE_VECTOR_REGISTERS2();
2271
        if (ret != 0) {
2272
#ifdef WC_C_DYNAMIC_FALLBACK
2273
            sha3_block = BlockSha3;
2274
#else
2275
            return ret;
2276
#endif
2277
        }
2278
    }
2279
#endif /* USE_INTEL_SPEEDUP */
2280
2281
0
    for (; (blockCnt > 0); blockCnt--) {
2282
    #ifdef SHA3_FUNC_PTR
2283
        (*sha3_block)(shake->s);
2284
    #else
2285
0
        BlockSha3(shake->s);
2286
0
    #endif
2287
    #if defined(BIG_ENDIAN_ORDER)
2288
        ByteReverseWords64((word64*)out, shake->s, WC_SHA3_128_COUNT * 8);
2289
    #elif defined(WOLFSSL_WIDE_BYTE)
2290
        Sha3SqueezeBytes(out, shake->s, WC_SHA3_128_COUNT * 8);
2291
    #else
2292
0
        XMEMCPY(out, shake->s, WC_SHA3_128_COUNT * 8);
2293
0
    #endif
2294
0
        out += WC_SHA3_128_COUNT * 8;
2295
0
    }
2296
2297
#ifdef USE_INTEL_SPEEDUP
2298
    if (SHA3_BLOCK_VREGS(sha3_block))
2299
        RESTORE_VECTOR_REGISTERS();
2300
#endif
2301
2302
0
    return 0;
2303
0
}
2304
#endif
2305
2306
2307
/* Dispose of any dynamically allocated data from the SHAKE128 operation.
2308
 * (Required for async ops.)
2309
 *
2310
 * shake  wc_Shake object holding state.
2311
 * returns 0 on success.
2312
 */
2313
void wc_Shake128_Free(wc_Shake* shake)
2314
0
{
2315
0
    wc_Sha3Free(shake);
2316
0
}
2317
2318
/* Copy the state of the SHA3-512 operation.
2319
 *
2320
 * src  wc_Shake object holding state top copy.
2321
 * dst  wc_Shake object to copy into.
2322
 * returns 0 on success.
2323
 */
2324
int wc_Shake128_Copy(wc_Shake* src, wc_Shake* dst)
2325
0
{
2326
0
    return wc_Sha3Copy(src, dst);
2327
0
}
2328
#endif
2329
2330
#ifdef WOLFSSL_SHAKE256
2331
/* Initialize the state for a Shake256 hash operation.
2332
 *
2333
 * shake  wc_Shake object holding state.
2334
 * heap   Heap reference for dynamic memory allocation. (Used in async ops.)
2335
 * devId  Device identifier for asynchronous operation.
2336
 * returns 0 on success.
2337
 */
2338
int wc_InitShake256(wc_Shake* shake, void* heap, int devId)
2339
0
{
2340
0
    int ret = wc_InitSha3(shake, heap, devId);
2341
/* The PSoC6 wc_Sha3 variant has no hashType member */
2342
#if defined(WOLF_CRYPTO_CB) && !defined(PSOC6_HASH_SHA3)
2343
    /* SHAKE never hits the SHA3 auto-detect, so set the type here for the
2344
     * Copy/Free callback dispatch. */
2345
    if (ret == 0)
2346
        shake->hashType = WC_HASH_TYPE_SHAKE256;
2347
#endif
2348
0
    return ret;
2349
0
}
2350
2351
2352
#ifdef PSOC6_HASH_SHA3
2353
2354
int wc_Shake256_Update(wc_Shake* shake, const byte* data, word32 len)
2355
{
2356
    int ret;
2357
    if (shake == NULL || (data == NULL && len > 0)) {
2358
         return BAD_FUNC_ARG;
2359
    }
2360
2361
    if (data == NULL) {
2362
        /* len is 0 here: valid, but do nothing */
2363
        return 0;
2364
    }
2365
2366
    /* Lock the mutex to perform crypto operations */
2367
    ret = wolfSSL_CryptHwMutexLock();
2368
    if (ret == 0) {
2369
        /* Perform SHA3 on the input data and update the hash state */
2370
        ret = wc_Psoc6_Sha3_Update(shake, data, len, WC_SHA3_256_COUNT);
2371
        /* Release the lock */
2372
        wolfSSL_CryptHwMutexUnLock();
2373
    }
2374
2375
    return ret;
2376
}
2377
2378
int wc_Shake256_Final(wc_Shake* shake, byte* hash, word32 hashLen)
2379
{
2380
    int ret;
2381
    if (shake == NULL || hash == NULL) {
2382
        return BAD_FUNC_ARG;
2383
    }
2384
2385
    /* Lock the mutex to perform crypto operations */
2386
    ret = wolfSSL_CryptHwMutexLock();
2387
    if (ret == 0) {
2388
        /* Finalize SHA3 operations and produce digest */
2389
        ret = wc_Psoc6_Sha3_Final(shake, 0x1f, hash, WC_SHA3_256_COUNT, hashLen);
2390
        if (ret == 0) {
2391
            /* Initialize hash state for SHA-3 operation */
2392
            ret = wc_Psoc6_Sha3_Init(shake);
2393
        }
2394
        /* Release the lock */
2395
        wolfSSL_CryptHwMutexUnLock();
2396
    }
2397
2398
    return ret;
2399
}
2400
2401
int wc_Shake256_Absorb(wc_Shake* shake, const byte* data, word32 len)
2402
{
2403
    int ret;
2404
2405
    if ((shake == NULL) || (data == NULL && len != 0)) {
2406
        return BAD_FUNC_ARG;
2407
    }
2408
2409
    /* Lock the mutex to perform crypto operations */
2410
    ret = wolfSSL_CryptHwMutexLock();
2411
    if (ret == 0) {
2412
        /* Perform SHA3 on the input data and update the hash state */
2413
        ret = wc_Psoc6_Sha3_Update(shake, data, len, WC_SHA3_256_COUNT);
2414
        if (ret == 0) {
2415
            /* Finalize SHA3 operations and produce digest */
2416
            ret = wc_Psoc6_Sha3_Final(shake, 0x1f, NULL, WC_SHA3_256_COUNT, 0);
2417
        }
2418
        /* Release the lock */
2419
        wolfSSL_CryptHwMutexUnLock();
2420
    }
2421
2422
    return ret;
2423
}
2424
2425
int wc_Shake256_SqueezeBlocks(wc_Shake* shake, byte* out, word32 blockCnt)
2426
{
2427
    int ret;
2428
    if ((shake == NULL) || (out == NULL && blockCnt != 0)) {
2429
        return BAD_FUNC_ARG;
2430
    }
2431
2432
    /* Lock the mutex to perform crypto operations */
2433
    ret = wolfSSL_CryptHwMutexLock();
2434
    if (ret == 0) {
2435
        /* Squeeze output blocks from current hash state */
2436
        ret = wc_Psoc6_Shake_SqueezeBlocks(shake, out, blockCnt);
2437
        /* Release the lock */
2438
        wolfSSL_CryptHwMutexUnLock();
2439
    }
2440
2441
    return ret;
2442
}
2443
2444
#else
2445
/* Update the SHAKE256 hash state with message data.
2446
 *
2447
 * shake  wc_Shake object holding state.
2448
 * data  Message data to be hashed.
2449
 * len   Length of the message data.
2450
 * returns 0 on success.
2451
 */
2452
int wc_Shake256_Update(wc_Shake* shake, const byte* data, word32 len)
2453
0
{
2454
0
    if (shake == NULL) {
2455
0
        return BAD_FUNC_ARG;
2456
0
    }
2457
2458
0
    if (data == NULL && len == 0) {
2459
        /* valid, but do nothing */
2460
0
        return 0;
2461
0
    }
2462
2463
0
    if (data == NULL) {
2464
0
        return BAD_FUNC_ARG;
2465
0
    }
2466
2467
#ifdef WOLF_CRYPTO_CB
2468
    #ifndef WOLF_CRYPTO_CB_FIND
2469
    if (shake->devId != INVALID_DEVID)
2470
    #endif
2471
    {
2472
        int ret = wc_CryptoCb_Shake(shake, WC_HASH_TYPE_SHAKE256, data, len,
2473
            NULL, 0);
2474
        if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE))
2475
            return ret;
2476
        /* fall-through when unavailable */
2477
    }
2478
#endif
2479
2480
0
    return Sha3Update(shake, data, len, WC_SHA3_256_COUNT);
2481
0
}
2482
2483
/* Calculate the SHAKE256 hash based on all the message data seen.
2484
 * The state is initialized ready for a new message to hash.
2485
 *
2486
 * shake  wc_Shake object holding state.
2487
 * hash  Buffer to hold the hash result. Must be at least 64 bytes.
2488
 * hashLen Size of hash in bytes.
2489
 * returns 0 on success.
2490
 */
2491
int wc_Shake256_Final(wc_Shake* shake, byte* hash, word32 hashLen)
2492
0
{
2493
0
    int ret;
2494
2495
0
    if (shake == NULL || hash == NULL) {
2496
0
        return BAD_FUNC_ARG;
2497
0
    }
2498
2499
#ifdef WOLF_CRYPTO_CB
2500
    #ifndef WOLF_CRYPTO_CB_FIND
2501
    if (shake->devId != INVALID_DEVID)
2502
    #endif
2503
    {
2504
        ret = wc_CryptoCb_Shake(shake, WC_HASH_TYPE_SHAKE256, NULL, 0, hash,
2505
            hashLen);
2506
        if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE))
2507
            return ret;
2508
        /* fall-through when unavailable */
2509
    }
2510
#endif
2511
2512
0
    ret = Sha3Final(shake, 0x1f, hash, WC_SHA3_256_COUNT, hashLen);
2513
0
    if (ret != 0)
2514
0
        return ret;
2515
2516
0
    ret = InitSha3(shake);  /* reset state */
2517
#ifdef WOLF_CRYPTO_CB
2518
    /* Restore the type cleared by the reset for Copy/Free dispatch. */
2519
    if (ret == 0)
2520
        shake->hashType = WC_HASH_TYPE_SHAKE256;
2521
#endif
2522
0
    return ret;
2523
0
}
2524
2525
/* Absorb the data for squeezing.
2526
 *
2527
 * Update and final with data but no output and no reset
2528
 *
2529
 * shake  wc_Shake object holding state.
2530
 * data  Data to absorb.
2531
 * len  Length of d to absorb in bytes.
2532
 * returns 0 on success.
2533
 */
2534
int wc_Shake256_Absorb(wc_Shake* shake, const byte* data, word32 len)
2535
0
{
2536
0
    int ret;
2537
2538
0
    if ((shake == NULL) || (data == NULL && len != 0)) {
2539
0
        return BAD_FUNC_ARG;
2540
0
    }
2541
2542
0
    ret = Sha3Update(shake, data, len, WC_SHA3_256_COUNT);
2543
0
    if (ret == 0) {
2544
0
        byte hash[1];
2545
0
        ret = Sha3Final(shake, 0x1f, hash, WC_SHA3_256_COUNT, 0);
2546
0
    }
2547
    /* No partial data. */
2548
0
    shake->i = 0;
2549
2550
0
    return ret;
2551
0
}
2552
2553
/* Squeeze the state to produce pseudo-random output.
2554
 *
2555
 * shake  wc_Shake object holding state.
2556
 * out  Output buffer.
2557
 * blockCnt  Number of blocks to write.
2558
 * returns 0 on success.
2559
 */
2560
int wc_Shake256_SqueezeBlocks(wc_Shake* shake, byte* out, word32 blockCnt)
2561
0
{
2562
#if defined(WC_C_DYNAMIC_FALLBACK) && defined(USE_INTEL_SPEEDUP)
2563
    void (*sha3_block)(word64 *s);
2564
#endif
2565
2566
0
    if ((shake == NULL) || (out == NULL && blockCnt != 0)) {
2567
0
        return BAD_FUNC_ARG;
2568
0
    }
2569
2570
#ifdef USE_INTEL_SPEEDUP
2571
#ifdef WC_C_DYNAMIC_FALLBACK
2572
    sha3_block = SHA3_BLOCK;
2573
#endif
2574
2575
    if (SHA3_BLOCK_VREGS(sha3_block)) {
2576
        int ret = SAVE_VECTOR_REGISTERS2();
2577
        if (ret != 0) {
2578
#ifdef WC_C_DYNAMIC_FALLBACK
2579
            sha3_block = BlockSha3;
2580
#else
2581
            return ret;
2582
#endif
2583
        }
2584
    }
2585
#endif /* USE_INTEL_SPEEDUP */
2586
2587
0
    for (; (blockCnt > 0); blockCnt--) {
2588
    #ifdef SHA3_FUNC_PTR
2589
        (*sha3_block)(shake->s);
2590
    #else
2591
0
        BlockSha3(shake->s);
2592
0
    #endif
2593
    #if defined(BIG_ENDIAN_ORDER)
2594
        ByteReverseWords64((word64*)out, shake->s, WC_SHA3_256_COUNT * 8);
2595
    #elif defined(WOLFSSL_WIDE_BYTE)
2596
        Sha3SqueezeBytes(out, shake->s, WC_SHA3_256_COUNT * 8);
2597
    #else
2598
0
        XMEMCPY(out, shake->s, WC_SHA3_256_COUNT * 8);
2599
0
    #endif
2600
0
        out += WC_SHA3_256_COUNT * 8;
2601
0
    }
2602
2603
#ifdef USE_INTEL_SPEEDUP
2604
    if (SHA3_BLOCK_VREGS(sha3_block))
2605
        RESTORE_VECTOR_REGISTERS();
2606
#endif
2607
2608
0
    return 0;
2609
0
}
2610
#endif
2611
2612
/* Dispose of any dynamically allocated data from the SHAKE256 operation.
2613
 * (Required for async ops.)
2614
 *
2615
 * shake  wc_Shake object holding state.
2616
 * returns 0 on success.
2617
 */
2618
void wc_Shake256_Free(wc_Shake* shake)
2619
0
{
2620
0
    wc_Sha3Free(shake);
2621
0
}
2622
2623
/* Copy the state of the SHA3-512 operation.
2624
 *
2625
 * src  wc_Shake object holding state top copy.
2626
 * dst  wc_Shake object to copy into.
2627
 * returns 0 on success.
2628
 */
2629
int wc_Shake256_Copy(wc_Shake* src, wc_Shake* dst)
2630
0
{
2631
0
    return wc_Sha3Copy(src, dst);
2632
0
}
2633
#endif
2634
2635
#if (defined(WOLFSSL_KMAC) || defined(WOLFSSL_CSHAKE)) && \
2636
    defined(WC_SHA3_SW_KECCAK)
2637
/* cSHAKE and KMAC - NIST SP 800-185.
2638
 *
2639
 * cSHAKE is a customizable SHAKE; KMAC is cSHAKE keyed with the function name
2640
 * "KMAC". Both feed length-prefixed strings into the SHAKE (KECCAK) sponge and
2641
 * (when customized) finalize with the cSHAKE domain-separation pad byte 0x04
2642
 * rather than SHAKE's 0x1f. The heavy lifting - absorbing message bytes and
2643
 * squeezing output - reuses the software Sha3Update()/Sha3Final() helpers
2644
 * above. The KMAC-specific code is compiled only when WOLFSSL_KMAC is set;
2645
 * cSHAKE is also available on its own via WOLFSSL_CSHAKE. */
2646
2647
/* left_encode(value) per NIST SP 800-185, section 2.3.1.
2648
 *
2649
 * A length byte giving the number of value bytes, followed by that many bytes
2650
 * of the value in big-endian (most significant first) order.
2651
 *
2652
 * @param [out] out    Buffer to write encoding to. Must hold at least 9 bytes.
2653
 * @param [in]  value  Value to encode. 0 encodes as the bytes 0x01 0x00.
2654
 *
2655
 * @return  Number of bytes written to out - between 2 and 9.
2656
 */
2657
static word32 KmacLeftEncode(byte* out, word64 value)
2658
{
2659
    word32 n = 1;
2660
    word64 v = value;
2661
2662
    /* Build up the number of significant bytes (min 1) by halving: test the
2663
     * top 32 bits, then each smaller half, shifting away counted bytes. */
2664
    if ((v >> 32) != 0) { n += 4; v >>= 32; }
2665
    if ((v >> 16) != 0) { n += 2; v >>= 16; }
2666
    if ((v >>  8) != 0) { n += 1;           }
2667
2668
    /* Length byte then the n value bytes big-endian.  Enter the switch at
2669
     * case n and fall through, storing least-significant byte first into
2670
     * out[n]..out[1]. */
2671
    out[0] = (byte)n;
2672
    switch (n) {
2673
        case 8: out[8] = (byte)value; value >>= 8; FALL_THROUGH;
2674
        case 7: out[7] = (byte)value; value >>= 8; FALL_THROUGH;
2675
        case 6: out[6] = (byte)value; value >>= 8; FALL_THROUGH;
2676
        case 5: out[5] = (byte)value; value >>= 8; FALL_THROUGH;
2677
        case 4: out[4] = (byte)value; value >>= 8; FALL_THROUGH;
2678
        case 3: out[3] = (byte)value; value >>= 8; FALL_THROUGH;
2679
        case 2: out[2] = (byte)value; value >>= 8; FALL_THROUGH;
2680
        default: out[1] = (byte)value;
2681
    }
2682
2683
    return n + 1;
2684
}
2685
2686
#ifdef WOLFSSL_KMAC
2687
/* right_encode(value) per NIST SP 800-185, section 2.3.1. Only used by KMAC
2688
 * (cSHAKE does not bind an output length).
2689
 *
2690
 * The value in big-endian (most significant first) order, followed by a length
2691
 * byte giving the number of value bytes.
2692
 *
2693
 * @param [out] out    Buffer to write encoding to. Must hold at least 9 bytes.
2694
 * @param [in]  value  Value to encode. 0 encodes as the bytes 0x00 0x01.
2695
 *
2696
 * @return  Number of bytes written to out - between 2 and 9.
2697
 */
2698
static word32 KmacRightEncode(byte* out, word64 value)
2699
{
2700
    word32 n = 1;
2701
    word64 v = value;
2702
2703
    /* Build up the number of significant bytes (min 1) by halving: test the
2704
     * top 32 bits, then each smaller half, shifting away counted bytes. */
2705
    if ((v >> 32) != 0) { n += 4; v >>= 32; }
2706
    if ((v >> 16) != 0) { n += 2; v >>= 16; }
2707
    if ((v >>  8) != 0) { n += 1;           }
2708
2709
    /* The n value bytes big-endian then the length byte.  Enter the switch at
2710
     * case n and fall through, storing least-significant byte first into
2711
     * out[n-1]..out[0]. */
2712
    switch (n) {
2713
        case 8: out[7] = (byte)value; value >>= 8; FALL_THROUGH;
2714
        case 7: out[6] = (byte)value; value >>= 8; FALL_THROUGH;
2715
        case 6: out[5] = (byte)value; value >>= 8; FALL_THROUGH;
2716
        case 5: out[4] = (byte)value; value >>= 8; FALL_THROUGH;
2717
        case 4: out[3] = (byte)value; value >>= 8; FALL_THROUGH;
2718
        case 3: out[2] = (byte)value; value >>= 8; FALL_THROUGH;
2719
        case 2: out[1] = (byte)value; value >>= 8; FALL_THROUGH;
2720
        default: out[0] = (byte)value;
2721
    }
2722
    out[n] = (byte)n;
2723
2724
    return n + 1;
2725
}
2726
#endif /* WOLFSSL_KMAC */
2727
2728
/* Zero-pad the current bytepad() block, per NIST SP 800-185, section 2.3.3.
2729
 *
2730
 * Fills the tail of the current block with zeros so the number of bytes fed
2731
 * into the bytepad() block becomes a multiple of the KECCAK rate, then flushes
2732
 * the completed block.  The block offset is the sponge's own shake->i.
2733
 *
2734
 * @param [in,out] shake  SHAKE (KECCAK) object holding the sponge state.
2735
 * @param [in]     count  KECCAK 64-bit words per block - rate / 8.
2736
 * @param [in]     rate   KECCAK rate in bytes - the block size.
2737
 *
2738
 * @return  0 on success.
2739
 * @return  Negative error code from the sponge update on failure.
2740
 */
2741
static int CshakeBytePad(wc_Sha3* shake, word32 count, word32 rate)
2742
{
2743
    int    ret = 0;
2744
    word32 pad = (rate - shake->i) % rate;
2745
2746
    if (pad > 0) {
2747
        /* Zero the rest of the block in place and flush it - a zero-length
2748
         * update with i == rate triggers the XOR-in and permutation. */
2749
        XMEMSET(shake->t + shake->i, 0, pad);
2750
        shake->i = rate;
2751
        ret = Sha3Update(shake, shake->t, 0, count);
2752
    }
2753
    return ret;
2754
}
2755
2756
/* Absorb the leading customization block shared by cSHAKE and KMAC:
2757
 *   bytepad(encode_string(name) || encode_string(custom), rate)
2758
 * (NIST SP 800-185, sections 3.2 and 3.3).
2759
 *
2760
 * Only ever called right after Init, so the sponge is fresh (shake->i is 0
2761
 * and shake->t is all zero). When the whole bytepad content fits in one block
2762
 * (the common case) it is copied straight into the block buffer and flushed
2763
 * once; otherwise the parts that may cross a block boundary go through
2764
 * Sha3Update.
2765
 *
2766
 * @param [in,out] shake      SHAKE (KECCAK) object holding the sponge state.
2767
 * @param [in]     count      KECCAK 64-bit words per block - rate / 8.
2768
 * @param [in]     name       Function-name string, NULL when nameLen is 0.
2769
 * @param [in]     nameLen    Length of name in bytes.
2770
 * @param [in]     custom     Customization string, NULL when customLen is 0.
2771
 * @param [in]     customLen  Length of custom in bytes.
2772
 *
2773
 * @return  0 on success.
2774
 * @return  Negative error code from the sponge update on failure.
2775
 */
2776
static int CshakeAbsorbBlock(wc_Sha3* shake, word32 count, const byte* name,
2777
    word32 nameLen, const byte* custom, word32 customLen)
2778
{
2779
    word32 rate = count * 8U;
2780
    byte   enc[9];
2781
    word32 e;
2782
    word32 h;
2783
    word32 avail;
2784
    int    ret = 0;
2785
2786
    /* left_encode(rate) || left_encode(nameLen * 8) straight into the block
2787
     * buffer - fits at the start of a fresh block. */
2788
    h  = KmacLeftEncode(shake->t, (word64)rate);
2789
    h += KmacLeftEncode(shake->t + h, (word64)nameLen * 8);
2790
    e  = KmacLeftEncode(enc, (word64)customLen * 8);
2791
    avail = rate - h;
2792
2793
    /* Common case: the whole bytepad content fits in this one block, so copy
2794
     * name || left_encode(customLen*8) || custom straight in and let the pad
2795
     * flush it - no per-piece Sha3Update.  Conditions are ordered to avoid
2796
     * word32 overflow when name/custom are large. */
2797
    if ((nameLen < avail) && (e < avail - nameLen) &&
2798
            (customLen < avail - nameLen - e)) {
2799
        if (nameLen > 0) {
2800
            XMEMCPY(shake->t + h, name, nameLen);
2801
            h += nameLen;
2802
        }
2803
        XMEMCPY(shake->t + h, enc, e);
2804
        h += e;
2805
        if (customLen > 0) {
2806
            XMEMCPY(shake->t + h, custom, customLen);
2807
            h += customLen;
2808
        }
2809
        shake->i = h;
2810
    }
2811
    else {
2812
        /* name and/or custom cross a block boundary - absorb them. */
2813
        shake->i = h;
2814
        if (nameLen > 0) {
2815
            ret = Sha3Update(shake, name, nameLen, count);
2816
        }
2817
        if (ret == 0) {
2818
            ret = Sha3Update(shake, enc, e, count);
2819
        }
2820
        if ((ret == 0) && (customLen > 0)) {
2821
            ret = Sha3Update(shake, custom, customLen, count);
2822
        }
2823
    }
2824
2825
    /* bytepad zero-fill - shake->i already tracks the block offset. */
2826
    if (ret == 0) {
2827
        ret = CshakeBytePad(shake, count, rate);
2828
    }
2829
    return ret;
2830
}
2831
2832
#ifdef WOLFSSL_KMAC
2833
/* Initialize a KMAC operation for the given KECCAK block count.
2834
 *
2835
 * count is WC_SHA3_128_COUNT for KMAC128 or WC_SHA3_256_COUNT for KMAC256.
2836
 * Absorbs the two leading cSHAKE/KMAC bytepad blocks, leaving the sponge ready
2837
 * for message data (NIST SP 800-185, sections 3.2 and 4.3):
2838
 *   bytepad(encode_string("KMAC") || encode_string(custom), rate)
2839
 *   bytepad(encode_string(key), rate)
2840
 *
2841
 * @param [out] kmac       KMAC object to initialize.
2842
 * @param [in]  count      KECCAK 64-bit words per block - rate / 8.
2843
 * @param [in]  key        Key bytes.
2844
 * @param [in]  keyLen     Length of key in bytes.
2845
 * @param [in]  custom     Customization string, or NULL when customLen is 0.
2846
 * @param [in]  customLen  Length of custom in bytes.
2847
 * @param [in]  heap       Dynamic memory hint.
2848
 * @param [in]  devId      Device identifier.
2849
 *
2850
 * @return  0 on success.
2851
 * @return  BAD_FUNC_ARG when a NULL pointer has a non-zero length.
2852
 * @return  Negative error code from the sponge update on failure.
2853
 */
2854
static int KmacInit(wc_Kmac* kmac, word32 count, const byte* key, word32 keyLen,
2855
    const byte* custom, word32 customLen, void* heap, int devId)
2856
{
2857
    /* The KMAC function name string "KMAC". */
2858
    static const byte kmacName[4] = { 0x4b, 0x4d, 0x41, 0x43 };
2859
    word32 rate;
2860
    int    ret;
2861
2862
    if ((kmac == NULL) || ((key == NULL) && (keyLen != 0)) ||
2863
            ((custom == NULL) && (customLen != 0))) {
2864
        ret = BAD_FUNC_ARG;
2865
    }
2866
#ifdef HAVE_FIPS
2867
    else if (keyLen < KMAC_FIPS_MIN_KEY) {
2868
        ret = KMAC_MIN_KEYLEN_E;
2869
    }
2870
#endif
2871
    else {
2872
        kmac->count = count;
2873
        rate = count * 8U;
2874
        ret = wc_InitSha3(&kmac->shake, heap, devId);
2875
2876
        /* bytepad(encode_string("KMAC") || encode_string(custom), rate) */
2877
        if (ret == 0) {
2878
            ret = CshakeAbsorbBlock(&kmac->shake, count, kmacName,
2879
                (word32)sizeof(kmacName), custom, customLen);
2880
        }
2881
2882
        /* bytepad(encode_string(key), rate).  The block above flushed, so the
2883
         * sponge is at a block boundary (shake->i == 0) - write the length
2884
         * encodings straight into the block buffer, as in CshakeAbsorbBlock. */
2885
        if (ret == 0) {
2886
            word32 h;
2887
2888
            h  = KmacLeftEncode(kmac->shake.t, (word64)rate);
2889
            h += KmacLeftEncode(kmac->shake.t + h, (word64)keyLen * 8);
2890
            kmac->shake.i = h;
2891
2892
            if (keyLen > 0) {
2893
                /* Copy a key that fits into the block straight in and flush
2894
                 * once; a longer key crosses a boundary so is absorbed. */
2895
                if (keyLen < rate - h) {
2896
                    XMEMCPY(kmac->shake.t + h, key, keyLen);
2897
                    kmac->shake.i += keyLen;
2898
                }
2899
                else {
2900
                    ret = Sha3Update(&kmac->shake, key, keyLen, count);
2901
                }
2902
            }
2903
            if (ret == 0) {
2904
                ret = CshakeBytePad(&kmac->shake, count, rate);
2905
            }
2906
        }
2907
    }
2908
2909
    return ret;
2910
}
2911
2912
/* Absorb message data into a KMAC operation.
2913
 *
2914
 * @param [in,out] kmac   KMAC object holding the sponge state.
2915
 * @param [in]     in     Message bytes, or NULL when inLen is 0.
2916
 * @param [in]     inLen  Length of in in bytes.
2917
 *
2918
 * @return  0 on success.
2919
 * @return  BAD_FUNC_ARG on a NULL message with a non-zero length.
2920
 * @return  Negative error code from the sponge update on failure.
2921
 */
2922
static int KmacUpdate(wc_Kmac* kmac, const byte* in, word32 inLen)
2923
{
2924
    int ret;
2925
2926
    if ((kmac == NULL) || ((in == NULL) && (inLen != 0))) {
2927
        ret = BAD_FUNC_ARG;
2928
    }
2929
    else {
2930
        ret = Sha3Update(&kmac->shake, in, inLen, kmac->count);
2931
    }
2932
    return ret;
2933
}
2934
2935
/* Finalize a KMAC operation, producing outLen bytes of output.
2936
 *
2937
 * For fixed-length KMAC (xof == 0) the requested length is encoded into the
2938
 * message (right_encode(outLen * 8)) before the cSHAKE pad, so changing outLen
2939
 * changes the whole result - as required by SP 800-185. For the XOF variant
2940
 * (xof != 0) right_encode(0) is used and any number of output bytes may be
2941
 * produced without changing the leading bytes.
2942
 *
2943
 * @param [in,out] kmac    KMAC object holding the sponge state.
2944
 * @param [out]    out     Buffer to hold output.
2945
 * @param [in]     outLen  Number of output bytes to produce.
2946
 * @param [in]     xof     Non-zero to finalize as an XOF - encode length 0.
2947
 *
2948
 * @return  0 on success.
2949
 * @return  BAD_FUNC_ARG when kmac or out is NULL.
2950
 * @return  Negative error code from the sponge on failure.
2951
 */
2952
static int KmacFinal(wc_Kmac* kmac, byte* out, word32 outLen, int xof)
2953
{
2954
    word32 rate;
2955
    int    ret = 0;
2956
2957
    if ((kmac == NULL) || (out == NULL)) {
2958
        ret = BAD_FUNC_ARG;
2959
    }
2960
#ifdef HAVE_FIPS
2961
    else if ((xof == 0) && (outLen < KMAC_FIPS_MIN_OUTPUT)) {
2962
        ret = BAD_LENGTH_E;
2963
    }
2964
#endif
2965
    else if ((kmac->count < WC_SHA3_512_COUNT) ||
2966
             (kmac->count > WC_SHA3_128_COUNT) ||
2967
             (kmac->shake.i >= kmac->count * 8U)) {
2968
        ret = BAD_STATE_E;
2969
    }
2970
    else {
2971
        /* right_encode(outLen * 8), or right_encode(0) for the XOF. */
2972
        word64 v = xof ? (word64)0 : (word64)outLen * 8;
2973
        rate = kmac->count * 8U;
2974
2975
        /* The encoding is at most 9 bytes; when that many fit in the current
2976
         * block, write it straight into the block buffer, otherwise use a
2977
         * temporary and Sha3Update (which handles crossing the boundary). */
2978
        if (kmac->shake.i + 9 < rate) {
2979
            word32 l = KmacRightEncode(kmac->shake.t + kmac->shake.i, v);
2980
            kmac->shake.i += l;
2981
        }
2982
        else {
2983
            byte   enc[9];
2984
            word32 encLen = KmacRightEncode(enc, v);
2985
            ret = Sha3Update(&kmac->shake, enc, encLen, kmac->count);
2986
        }
2987
        if (ret == 0) {
2988
            /* cSHAKE domain separation pad (0x04), then squeeze outLen. */
2989
            ret = Sha3Final(&kmac->shake, 0x04, out, kmac->count, outLen);
2990
        }
2991
    }
2992
    return ret;
2993
}
2994
2995
/* Copy the state of a KMAC operation so it can be finalized more than once
2996
 * (for example over a common prefix).
2997
 *
2998
 * dst must be an initialized wc_Kmac: the copy releases any resources it
2999
 * already holds before overwriting it (as with wc_Sha3Copy/wc_Shake_Copy).
3000
 *
3001
 * @param [in]  src  KMAC object to copy from.
3002
 * @param [out] dst  Initialized KMAC object to copy into.
3003
 *
3004
 * @return  0 on success.
3005
 * @return  BAD_FUNC_ARG when src or dst is NULL.
3006
 * @return  Negative error code from the sponge copy on failure.
3007
 */
3008
static int KmacCopy(wc_Kmac* src, wc_Kmac* dst)
3009
{
3010
    int ret;
3011
3012
    if ((src == NULL) || (dst == NULL)) {
3013
        ret = BAD_FUNC_ARG;
3014
    }
3015
    else {
3016
        ret = wc_Sha3Copy(&src->shake, &dst->shake);
3017
        if (ret == 0) {
3018
            dst->count = src->count;
3019
        }
3020
    }
3021
    return ret;
3022
}
3023
#endif /* WOLFSSL_KMAC */
3024
3025
#if defined(WOLFSSL_CSHAKE128) || defined(WOLFSSL_CSHAKE256)
3026
/* Initialize a cSHAKE operation for the given KECCAK block count.
3027
 *
3028
 * count is WC_SHA3_128_COUNT for cSHAKE128 or WC_SHA3_256_COUNT for cSHAKE256.
3029
 * When both the function-name and customization strings are empty, cSHAKE is
3030
 * defined to reduce to plain SHAKE (NIST SP 800-185, section 3.3), so no
3031
 * customization block is absorbed and the SHAKE pad (0x1f) is used.
3032
 *
3033
 * @param [out] cshake     cSHAKE object to initialize.
3034
 * @param [in]  count      KECCAK 64-bit words per block - rate / 8.
3035
 * @param [in]  name       Function-name string, or NULL when nameLen is 0.
3036
 * @param [in]  nameLen    Length of name in bytes.
3037
 * @param [in]  custom     Customization string, or NULL when customLen is 0.
3038
 * @param [in]  customLen  Length of custom in bytes.
3039
 * @param [in]  heap       Dynamic memory hint.
3040
 * @param [in]  devId      Device identifier.
3041
 *
3042
 * @return  0 on success.
3043
 * @return  BAD_FUNC_ARG when a NULL pointer has a non-zero length.
3044
 * @return  Negative error code from the sponge update on failure.
3045
 */
3046
static int CshakeInit(wc_Cshake* cshake, word32 count, const byte* name,
3047
    word32 nameLen, const byte* custom, word32 customLen, void* heap, int devId)
3048
{
3049
    int ret;
3050
3051
    if ((cshake == NULL) || ((name == NULL) && (nameLen != 0)) ||
3052
            ((custom == NULL) && (customLen != 0))) {
3053
        ret = BAD_FUNC_ARG;
3054
    }
3055
    else {
3056
        cshake->count = count;
3057
        ret = wc_InitSha3(&cshake->shake, heap, devId);
3058
        if (ret == 0) {
3059
            if ((nameLen == 0) && (customLen == 0)) {
3060
                /* No customization: cSHAKE reduces to SHAKE. */
3061
                cshake->pad = 0x1f;
3062
            }
3063
            else {
3064
                cshake->pad = 0x04;
3065
                ret = CshakeAbsorbBlock(&cshake->shake, count, name, nameLen,
3066
                    custom, customLen);
3067
            }
3068
        }
3069
    }
3070
    return ret;
3071
}
3072
3073
/* Absorb message data into a cSHAKE operation.
3074
 *
3075
 * @param [in,out] cshake  cSHAKE object holding the sponge state.
3076
 * @param [in]     in      Message bytes, or NULL when inLen is 0.
3077
 * @param [in]     inLen   Length of in in bytes.
3078
 *
3079
 * @return  0 on success.
3080
 * @return  BAD_FUNC_ARG on a NULL message with a non-zero length.
3081
 * @return  Negative error code from the sponge update on failure.
3082
 */
3083
static int CshakeUpdate(wc_Cshake* cshake, const byte* in, word32 inLen)
3084
{
3085
    int ret;
3086
3087
    if ((cshake == NULL) || ((in == NULL) && (inLen != 0))) {
3088
        ret = BAD_FUNC_ARG;
3089
    }
3090
    else {
3091
        ret = Sha3Update(&cshake->shake, in, inLen, cshake->count);
3092
    }
3093
    return ret;
3094
}
3095
3096
/* Finalize a cSHAKE operation, squeezing outLen bytes. cSHAKE is an XOF, so
3097
 * the output length is not bound into the result and a longer squeeze extends
3098
 * a shorter one.
3099
 *
3100
 * @param [in,out] cshake  cSHAKE object holding the sponge state.
3101
 * @param [out]    out     Buffer to hold output.
3102
 * @param [in]     outLen  Number of output bytes to produce.
3103
 *
3104
 * @return  0 on success.
3105
 * @return  BAD_FUNC_ARG when cshake or out is NULL.
3106
 * @return  Negative error code from the sponge on failure.
3107
 */
3108
static int CshakeFinal(wc_Cshake* cshake, byte* out, word32 outLen)
3109
{
3110
    int ret;
3111
3112
    if ((cshake == NULL) || (out == NULL)) {
3113
        ret = BAD_FUNC_ARG;
3114
    }
3115
    else {
3116
        ret = Sha3Final(&cshake->shake, cshake->pad, out, cshake->count,
3117
            outLen);
3118
    }
3119
    return ret;
3120
}
3121
3122
/* Copy the state of a cSHAKE operation so it can be finalized more than once
3123
 * (for example over a common message prefix).
3124
 *
3125
 * dst must be an initialized wc_Cshake: the copy releases any resources it
3126
 * already holds before overwriting it (as with wc_Sha3Copy/wc_Shake_Copy).
3127
 *
3128
 * @param [in]  src  cSHAKE object to copy from.
3129
 * @param [out] dst  Initialized cSHAKE object to copy into.
3130
 *
3131
 * @return  0 on success.
3132
 * @return  BAD_FUNC_ARG when src or dst is NULL.
3133
 * @return  Negative error code from the sponge copy on failure.
3134
 */
3135
static int CshakeCopy(wc_Cshake* src, wc_Cshake* dst)
3136
{
3137
    int ret;
3138
3139
    if ((src == NULL) || (dst == NULL)) {
3140
        ret = BAD_FUNC_ARG;
3141
    }
3142
    else {
3143
        ret = wc_Sha3Copy(&src->shake, &dst->shake);
3144
        if (ret == 0) {
3145
            dst->count = src->count;
3146
            dst->pad   = src->pad;
3147
        }
3148
    }
3149
    return ret;
3150
}
3151
#endif /* WOLFSSL_CSHAKE128 || WOLFSSL_CSHAKE256 */
3152
3153
#ifdef WOLFSSL_KMAC128
3154
/* Initialize a KMAC128 operation with a key and optional customization string.
3155
 *
3156
 * @param [out] kmac       wc_Kmac object to initialize.
3157
 * @param [in]  key        Key bytes.
3158
 * @param [in]  keyLen     Length of the key in bytes.
3159
 * @param [in]  custom     Customization string, or NULL when customLen is 0.
3160
 * @param [in]  customLen  Length of the customization string in bytes.
3161
 * @param [in]  heap       Dynamic memory hint.
3162
 * @param [in]  devId      Device identifier.
3163
 *
3164
 * @return  0 on success.
3165
 * @return  BAD_FUNC_ARG when a required pointer is NULL.
3166
 */
3167
int wc_InitKmac128(wc_Kmac* kmac, const byte* key, word32 keyLen,
3168
    const byte* custom, word32 customLen, void* heap, int devId)
3169
{
3170
    return KmacInit(kmac, WC_SHA3_128_COUNT, key, keyLen, custom, customLen,
3171
        heap, devId);
3172
}
3173
3174
/* Absorb message data into a KMAC128 operation.
3175
 *
3176
 * @param [in,out] kmac   wc_Kmac object holding state.
3177
 * @param [in]     in     Message bytes, or NULL when inLen is 0.
3178
 * @param [in]     inLen  Length of in in bytes.
3179
 *
3180
 * @return  0 on success.
3181
 * @return  BAD_FUNC_ARG on a NULL message with a non-zero length.
3182
 */
3183
int wc_Kmac128_Update(wc_Kmac* kmac, const byte* in, word32 inLen)
3184
{
3185
    return KmacUpdate(kmac, in, inLen);
3186
}
3187
3188
/* Finalize a KMAC128 operation, writing outLen bytes to out.
3189
 *
3190
 * The output length is bound into the result (NIST SP 800-185 KMAC).
3191
 *
3192
 * @param [in,out] kmac    wc_Kmac object holding state.
3193
 * @param [out]    out     Buffer to hold the output.
3194
 * @param [in]     outLen  Number of output bytes to produce.
3195
 *
3196
 * @return  0 on success.
3197
 * @return  BAD_FUNC_ARG when a parameter is NULL.
3198
 */
3199
int wc_Kmac128_Final(wc_Kmac* kmac, byte* out, word32 outLen)
3200
{
3201
    return KmacFinal(kmac, out, outLen, 0);
3202
}
3203
3204
/* Finalize a KMAC128 operation as an XOF - KMACXOF128.
3205
 *
3206
 * The output length is not bound into the result, so any amount of output may
3207
 * be requested.
3208
 *
3209
 * @param [in,out] kmac    wc_Kmac object holding state.
3210
 * @param [out]    out     Buffer to hold the output.
3211
 * @param [in]     outLen  Number of output bytes to produce.
3212
 *
3213
 * @return  0 on success.
3214
 * @return  BAD_FUNC_ARG when a parameter is NULL.
3215
 */
3216
int wc_Kmac128_FinalXof(wc_Kmac* kmac, byte* out, word32 outLen)
3217
{
3218
    return KmacFinal(kmac, out, outLen, 1);
3219
}
3220
3221
/* Copy the state of a KMAC128 operation, allowing it to be finalized more
3222
 * than once (for example over a common message prefix).
3223
 *
3224
 * @param [in]  src  wc_Kmac object to copy from.
3225
 * @param [out] dst  wc_Kmac object to copy into.
3226
 *
3227
 * @return  0 on success.
3228
 * @return  BAD_FUNC_ARG when src or dst is NULL.
3229
 */
3230
int wc_Kmac128_Copy(wc_Kmac* src, wc_Kmac* dst)
3231
{
3232
    return KmacCopy(src, dst);
3233
}
3234
3235
/* Dispose of any dynamically allocated data from a KMAC128 operation.
3236
 *
3237
 * The sponge state is key-derived, so it is zeroized on free, as with the
3238
 * other keyed MACs, HMAC and CMAC.
3239
 *
3240
 * @param [in,out] kmac  wc_Kmac object to free. May be NULL.
3241
 */
3242
void wc_Kmac128_Free(wc_Kmac* kmac)
3243
{
3244
    if (kmac != NULL) {
3245
        wc_Sha3Free(&kmac->shake);
3246
        ForceZero(kmac, sizeof(*kmac));
3247
    }
3248
}
3249
3250
/* One-shot KMAC128 over a single message.
3251
 *
3252
 * @param [in]  key        Key bytes.
3253
 * @param [in]  keyLen     Length of the key in bytes.
3254
 * @param [in]  custom     Customization string, or NULL when customLen is 0.
3255
 * @param [in]  customLen  Length of the customization string in bytes.
3256
 * @param [in]  in         Message bytes, or NULL when inLen is 0.
3257
 * @param [in]  inLen      Length of the message in bytes.
3258
 * @param [out] out        Buffer to hold the output.
3259
 * @param [in]  outLen     Number of output bytes to produce.
3260
 *
3261
 * @return  0 on success.
3262
 * @return  Negative error code on failure.
3263
 */
3264
int wc_Kmac128Hash(const byte* key, word32 keyLen, const byte* custom,
3265
    word32 customLen, const byte* in, word32 inLen, byte* out, word32 outLen)
3266
{
3267
    int ret = 0;
3268
    /* Heap-allocate the state on small-stack builds (it is ~400 bytes). */
3269
    WC_DECLARE_VAR(kmac, wc_Kmac, 1, NULL);
3270
3271
    WC_ALLOC_VAR_EX(kmac, wc_Kmac, 1, NULL, DYNAMIC_TYPE_TMP_BUFFER,
3272
        ret = MEMORY_E);
3273
3274
    if (ret == 0) {
3275
        ret = wc_InitKmac128(kmac, key, keyLen, custom, customLen, NULL,
3276
            INVALID_DEVID);
3277
    }
3278
    if (ret == 0) {
3279
        ret = wc_Kmac128_Update(kmac, in, inLen);
3280
    }
3281
    if (ret == 0) {
3282
        ret = wc_Kmac128_Final(kmac, out, outLen);
3283
    }
3284
    /* wc_Kmac128_Free tolerates a NULL pointer (allocation failure). */
3285
    wc_Kmac128_Free(kmac);
3286
    WC_FREE_VAR_EX(kmac, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3287
3288
    return ret;
3289
}
3290
3291
/* One-shot KMACXOF128 over a single message.
3292
 *
3293
 * As wc_Kmac128Hash(), but the output length is not bound into the result
3294
 * (KMACXOF128), so any amount of output may be requested.
3295
 *
3296
 * @param [in]  key        Key bytes.
3297
 * @param [in]  keyLen     Length of the key in bytes.
3298
 * @param [in]  custom     Customization string, or NULL when customLen is 0.
3299
 * @param [in]  customLen  Length of the customization string in bytes.
3300
 * @param [in]  in         Message bytes, or NULL when inLen is 0.
3301
 * @param [in]  inLen      Length of the message in bytes.
3302
 * @param [out] out        Buffer to hold the output.
3303
 * @param [in]  outLen     Number of output bytes to produce.
3304
 *
3305
 * @return  0 on success.
3306
 * @return  Negative error code on failure.
3307
 */
3308
int wc_Kmac128HashXof(const byte* key, word32 keyLen, const byte* custom,
3309
    word32 customLen, const byte* in, word32 inLen, byte* out, word32 outLen)
3310
{
3311
    int ret = 0;
3312
    /* Heap-allocate the state on small-stack builds (it is ~400 bytes). */
3313
    WC_DECLARE_VAR(kmac, wc_Kmac, 1, NULL);
3314
3315
    WC_ALLOC_VAR_EX(kmac, wc_Kmac, 1, NULL, DYNAMIC_TYPE_TMP_BUFFER,
3316
        ret = MEMORY_E);
3317
3318
    if (ret == 0) {
3319
        ret = wc_InitKmac128(kmac, key, keyLen, custom, customLen, NULL,
3320
            INVALID_DEVID);
3321
    }
3322
    if (ret == 0) {
3323
        ret = wc_Kmac128_Update(kmac, in, inLen);
3324
    }
3325
    if (ret == 0) {
3326
        ret = wc_Kmac128_FinalXof(kmac, out, outLen);
3327
    }
3328
    /* wc_Kmac128_Free tolerates a NULL pointer (allocation failure). */
3329
    wc_Kmac128_Free(kmac);
3330
    WC_FREE_VAR_EX(kmac, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3331
3332
    return ret;
3333
}
3334
#endif /* WOLFSSL_KMAC128 */
3335
3336
#ifdef WOLFSSL_KMAC256
3337
/* Initialize a KMAC256 operation with a key and optional customization string.
3338
 *
3339
 * @param [out] kmac       wc_Kmac object to initialize.
3340
 * @param [in]  key        Key bytes.
3341
 * @param [in]  keyLen     Length of the key in bytes.
3342
 * @param [in]  custom     Customization string, or NULL when customLen is 0.
3343
 * @param [in]  customLen  Length of the customization string in bytes.
3344
 * @param [in]  heap       Dynamic memory hint.
3345
 * @param [in]  devId      Device identifier.
3346
 *
3347
 * @return  0 on success.
3348
 * @return  BAD_FUNC_ARG when a required pointer is NULL.
3349
 */
3350
int wc_InitKmac256(wc_Kmac* kmac, const byte* key, word32 keyLen,
3351
    const byte* custom, word32 customLen, void* heap, int devId)
3352
{
3353
    return KmacInit(kmac, WC_SHA3_256_COUNT, key, keyLen, custom, customLen,
3354
        heap, devId);
3355
}
3356
3357
/* Absorb message data into a KMAC256 operation.
3358
 *
3359
 * @param [in,out] kmac   wc_Kmac object holding state.
3360
 * @param [in]     in     Message bytes, or NULL when inLen is 0.
3361
 * @param [in]     inLen  Length of in in bytes.
3362
 *
3363
 * @return  0 on success.
3364
 * @return  BAD_FUNC_ARG on a NULL message with a non-zero length.
3365
 */
3366
int wc_Kmac256_Update(wc_Kmac* kmac, const byte* in, word32 inLen)
3367
{
3368
    return KmacUpdate(kmac, in, inLen);
3369
}
3370
3371
/* Finalize a KMAC256 operation, writing outLen bytes to out.
3372
 *
3373
 * The output length is bound into the result (NIST SP 800-185 KMAC).
3374
 *
3375
 * @param [in,out] kmac    wc_Kmac object holding state.
3376
 * @param [out]    out     Buffer to hold the output.
3377
 * @param [in]     outLen  Number of output bytes to produce.
3378
 *
3379
 * @return  0 on success.
3380
 * @return  BAD_FUNC_ARG when a parameter is NULL.
3381
 */
3382
int wc_Kmac256_Final(wc_Kmac* kmac, byte* out, word32 outLen)
3383
{
3384
    return KmacFinal(kmac, out, outLen, 0);
3385
}
3386
3387
/* Finalize a KMAC256 operation as an XOF - KMACXOF256.
3388
 *
3389
 * The output length is not bound into the result, so any amount of output may
3390
 * be requested.
3391
 *
3392
 * @param [in,out] kmac    wc_Kmac object holding state.
3393
 * @param [out]    out     Buffer to hold the output.
3394
 * @param [in]     outLen  Number of output bytes to produce.
3395
 *
3396
 * @return  0 on success.
3397
 * @return  BAD_FUNC_ARG when a parameter is NULL.
3398
 */
3399
int wc_Kmac256_FinalXof(wc_Kmac* kmac, byte* out, word32 outLen)
3400
{
3401
    return KmacFinal(kmac, out, outLen, 1);
3402
}
3403
3404
/* Copy the state of a KMAC256 operation, allowing it to be finalized more
3405
 * than once (for example over a common message prefix).
3406
 *
3407
 * @param [in]  src  wc_Kmac object to copy from.
3408
 * @param [out] dst  wc_Kmac object to copy into.
3409
 *
3410
 * @return  0 on success.
3411
 * @return  BAD_FUNC_ARG when src or dst is NULL.
3412
 */
3413
int wc_Kmac256_Copy(wc_Kmac* src, wc_Kmac* dst)
3414
{
3415
    return KmacCopy(src, dst);
3416
}
3417
3418
/* Dispose of any dynamically allocated data from a KMAC256 operation.
3419
 *
3420
 * The sponge state is key-derived, so it is zeroized on free, as with the
3421
 * other keyed MACs, HMAC and CMAC.
3422
 *
3423
 * @param [in,out] kmac  wc_Kmac object to free. May be NULL.
3424
 */
3425
void wc_Kmac256_Free(wc_Kmac* kmac)
3426
{
3427
    if (kmac != NULL) {
3428
        wc_Sha3Free(&kmac->shake);
3429
        ForceZero(kmac, sizeof(*kmac));
3430
    }
3431
}
3432
3433
/* One-shot KMAC256 over a single message.
3434
 *
3435
 * @param [in]  key        Key bytes.
3436
 * @param [in]  keyLen     Length of the key in bytes.
3437
 * @param [in]  custom     Customization string, or NULL when customLen is 0.
3438
 * @param [in]  customLen  Length of the customization string in bytes.
3439
 * @param [in]  in         Message bytes, or NULL when inLen is 0.
3440
 * @param [in]  inLen      Length of the message in bytes.
3441
 * @param [out] out        Buffer to hold the output.
3442
 * @param [in]  outLen     Number of output bytes to produce.
3443
 *
3444
 * @return  0 on success.
3445
 * @return  Negative error code on failure.
3446
 */
3447
int wc_Kmac256Hash(const byte* key, word32 keyLen, const byte* custom,
3448
    word32 customLen, const byte* in, word32 inLen, byte* out, word32 outLen)
3449
{
3450
    int ret = 0;
3451
    /* Heap-allocate the state on small-stack builds (it is ~400 bytes). */
3452
    WC_DECLARE_VAR(kmac, wc_Kmac, 1, NULL);
3453
3454
    WC_ALLOC_VAR_EX(kmac, wc_Kmac, 1, NULL, DYNAMIC_TYPE_TMP_BUFFER,
3455
        ret = MEMORY_E);
3456
3457
    if (ret == 0) {
3458
        ret = wc_InitKmac256(kmac, key, keyLen, custom, customLen, NULL,
3459
            INVALID_DEVID);
3460
    }
3461
    if (ret == 0) {
3462
        ret = wc_Kmac256_Update(kmac, in, inLen);
3463
    }
3464
    if (ret == 0) {
3465
        ret = wc_Kmac256_Final(kmac, out, outLen);
3466
    }
3467
    /* wc_Kmac256_Free tolerates a NULL pointer (allocation failure). */
3468
    wc_Kmac256_Free(kmac);
3469
    WC_FREE_VAR_EX(kmac, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3470
3471
    return ret;
3472
}
3473
3474
/* One-shot KMACXOF256 over a single message.
3475
 *
3476
 * As wc_Kmac256Hash(), but the output length is not bound into the result
3477
 * (KMACXOF256), so any amount of output may be requested.
3478
 *
3479
 * @param [in]  key        Key bytes.
3480
 * @param [in]  keyLen     Length of the key in bytes.
3481
 * @param [in]  custom     Customization string, or NULL when customLen is 0.
3482
 * @param [in]  customLen  Length of the customization string in bytes.
3483
 * @param [in]  in         Message bytes, or NULL when inLen is 0.
3484
 * @param [in]  inLen      Length of the message in bytes.
3485
 * @param [out] out        Buffer to hold the output.
3486
 * @param [in]  outLen     Number of output bytes to produce.
3487
 *
3488
 * @return  0 on success.
3489
 * @return  Negative error code on failure.
3490
 */
3491
int wc_Kmac256HashXof(const byte* key, word32 keyLen, const byte* custom,
3492
    word32 customLen, const byte* in, word32 inLen, byte* out, word32 outLen)
3493
{
3494
    int ret = 0;
3495
    /* Heap-allocate the state on small-stack builds (it is ~400 bytes). */
3496
    WC_DECLARE_VAR(kmac, wc_Kmac, 1, NULL);
3497
3498
    WC_ALLOC_VAR_EX(kmac, wc_Kmac, 1, NULL, DYNAMIC_TYPE_TMP_BUFFER,
3499
        ret = MEMORY_E);
3500
3501
    if (ret == 0) {
3502
        ret = wc_InitKmac256(kmac, key, keyLen, custom, customLen, NULL,
3503
            INVALID_DEVID);
3504
    }
3505
    if (ret == 0) {
3506
        ret = wc_Kmac256_Update(kmac, in, inLen);
3507
    }
3508
    if (ret == 0) {
3509
        ret = wc_Kmac256_FinalXof(kmac, out, outLen);
3510
    }
3511
    /* wc_Kmac256_Free tolerates a NULL pointer (allocation failure). */
3512
    wc_Kmac256_Free(kmac);
3513
    WC_FREE_VAR_EX(kmac, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3514
3515
    return ret;
3516
}
3517
#endif /* WOLFSSL_KMAC256 */
3518
3519
#ifdef WOLFSSL_CSHAKE128
3520
/* Initialize a cSHAKE128 operation with a function-name and customization
3521
 * string (NIST SP 800-185). Enabled together with KMAC (WOLFSSL_KMAC).
3522
 *
3523
 * @param [out] cshake     wc_Cshake object to initialize.
3524
 * @param [in]  name       Function-name string, or NULL when nameLen is 0.
3525
 *                         Reserved for NIST-defined functions; use an empty
3526
 *                         string for application customization via custom.
3527
 * @param [in]  nameLen    Length of name in bytes.
3528
 * @param [in]  custom     Customization string, or NULL when customLen is 0.
3529
 * @param [in]  customLen  Length of the customization string in bytes.
3530
 * @param [in]  heap       Dynamic memory hint.
3531
 * @param [in]  devId      Device identifier.
3532
 *
3533
 * @return  0 on success.
3534
 * @return  BAD_FUNC_ARG when a required pointer is NULL.
3535
 */
3536
int wc_InitCshake128(wc_Cshake* cshake, const byte* name, word32 nameLen,
3537
    const byte* custom, word32 customLen, void* heap, int devId)
3538
{
3539
    return CshakeInit(cshake, WC_SHA3_128_COUNT, name, nameLen, custom,
3540
        customLen, heap, devId);
3541
}
3542
3543
/* Absorb message data into a cSHAKE128 operation.
3544
 *
3545
 * @param [in,out] cshake  wc_Cshake object holding state.
3546
 * @param [in]     in      Message bytes, or NULL when inLen is 0.
3547
 * @param [in]     inLen   Length of in in bytes.
3548
 *
3549
 * @return  0 on success.
3550
 * @return  BAD_FUNC_ARG on a NULL message with a non-zero length.
3551
 */
3552
int wc_Cshake128_Update(wc_Cshake* cshake, const byte* in, word32 inLen)
3553
{
3554
    return CshakeUpdate(cshake, in, inLen);
3555
}
3556
3557
/* Finalize a cSHAKE128 operation, writing outLen bytes to out.
3558
 *
3559
 * @param [in,out] cshake  wc_Cshake object holding state.
3560
 * @param [out]    out     Buffer to hold the output.
3561
 * @param [in]     outLen  Number of output bytes to produce.
3562
 *
3563
 * @return  0 on success.
3564
 * @return  BAD_FUNC_ARG when a parameter is NULL.
3565
 */
3566
int wc_Cshake128_Final(wc_Cshake* cshake, byte* out, word32 outLen)
3567
{
3568
    return CshakeFinal(cshake, out, outLen);
3569
}
3570
3571
/* Copy the state of a cSHAKE128 operation, allowing it to be finalized more
3572
 * than once (for example over a common message prefix). dst must already be
3573
 * an initialized wc_Cshake.
3574
 *
3575
 * @param [in]  src  wc_Cshake object to copy from.
3576
 * @param [out] dst  wc_Cshake object to copy into.
3577
 *
3578
 * @return  0 on success.
3579
 * @return  BAD_FUNC_ARG when src or dst is NULL.
3580
 */
3581
int wc_Cshake128_Copy(wc_Cshake* src, wc_Cshake* dst)
3582
{
3583
    return CshakeCopy(src, dst);
3584
}
3585
3586
/* Dispose of any dynamically allocated data from a cSHAKE128 operation.
3587
 *
3588
 * @param [in,out] cshake  wc_Cshake object to free. May be NULL.
3589
 */
3590
void wc_Cshake128_Free(wc_Cshake* cshake)
3591
{
3592
    if (cshake != NULL) {
3593
        wc_Sha3Free(&cshake->shake);
3594
    }
3595
}
3596
3597
/* One-shot cSHAKE128 over a single message.
3598
 *
3599
 * @param [in]  name       Function-name string, or NULL when nameLen is 0.
3600
 * @param [in]  nameLen    Length of name in bytes.
3601
 * @param [in]  custom     Customization string, or NULL when customLen is 0.
3602
 * @param [in]  customLen  Length of the customization string in bytes.
3603
 * @param [in]  in         Message bytes, or NULL when inLen is 0.
3604
 * @param [in]  inLen      Length of the message in bytes.
3605
 * @param [out] out        Buffer to hold the output.
3606
 * @param [in]  outLen     Number of output bytes to produce.
3607
 *
3608
 * @return  0 on success.
3609
 * @return  Negative error code on failure.
3610
 */
3611
int wc_Cshake128(const byte* name, word32 nameLen, const byte* custom,
3612
    word32 customLen, const byte* in, word32 inLen, byte* out, word32 outLen)
3613
{
3614
    int ret = 0;
3615
    /* Heap-allocate the state on small-stack builds (it is ~400 bytes). */
3616
    WC_DECLARE_VAR(cshake, wc_Cshake, 1, NULL);
3617
3618
    WC_ALLOC_VAR_EX(cshake, wc_Cshake, 1, NULL, DYNAMIC_TYPE_TMP_BUFFER,
3619
        ret = MEMORY_E);
3620
3621
    if (ret == 0) {
3622
        ret = wc_InitCshake128(cshake, name, nameLen, custom, customLen, NULL,
3623
            INVALID_DEVID);
3624
    }
3625
    if (ret == 0) {
3626
        ret = wc_Cshake128_Update(cshake, in, inLen);
3627
    }
3628
    if (ret == 0) {
3629
        ret = wc_Cshake128_Final(cshake, out, outLen);
3630
    }
3631
    /* wc_Cshake128_Free tolerates a NULL pointer (allocation failure). */
3632
    wc_Cshake128_Free(cshake);
3633
    WC_FREE_VAR_EX(cshake, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3634
3635
    return ret;
3636
}
3637
#endif /* WOLFSSL_CSHAKE128 */
3638
3639
#ifdef WOLFSSL_CSHAKE256
3640
/* Initialize a cSHAKE256 operation with a function-name and customization
3641
 * string. See wc_InitCshake128() for parameter details.
3642
 *
3643
 * @param [out] cshake     wc_Cshake object to initialize.
3644
 * @param [in]  name       Function-name string, or NULL when nameLen is 0.
3645
 * @param [in]  nameLen    Length of name in bytes.
3646
 * @param [in]  custom     Customization string, or NULL when customLen is 0.
3647
 * @param [in]  customLen  Length of the customization string in bytes.
3648
 * @param [in]  heap       Dynamic memory hint.
3649
 * @param [in]  devId      Device identifier.
3650
 *
3651
 * @return  0 on success.
3652
 * @return  BAD_FUNC_ARG when a required pointer is NULL.
3653
 */
3654
int wc_InitCshake256(wc_Cshake* cshake, const byte* name, word32 nameLen,
3655
    const byte* custom, word32 customLen, void* heap, int devId)
3656
{
3657
    return CshakeInit(cshake, WC_SHA3_256_COUNT, name, nameLen, custom,
3658
        customLen, heap, devId);
3659
}
3660
3661
/* Absorb message data into a cSHAKE256 operation.
3662
 *
3663
 * @param [in,out] cshake  wc_Cshake object holding state.
3664
 * @param [in]     in      Message bytes, or NULL when inLen is 0.
3665
 * @param [in]     inLen   Length of in in bytes.
3666
 *
3667
 * @return  0 on success.
3668
 * @return  BAD_FUNC_ARG on a NULL message with a non-zero length.
3669
 */
3670
int wc_Cshake256_Update(wc_Cshake* cshake, const byte* in, word32 inLen)
3671
{
3672
    return CshakeUpdate(cshake, in, inLen);
3673
}
3674
3675
/* Finalize a cSHAKE256 operation, writing outLen bytes to out.
3676
 *
3677
 * @param [in,out] cshake  wc_Cshake object holding state.
3678
 * @param [out]    out     Buffer to hold the output.
3679
 * @param [in]     outLen  Number of output bytes to produce.
3680
 *
3681
 * @return  0 on success.
3682
 * @return  BAD_FUNC_ARG when a parameter is NULL.
3683
 */
3684
int wc_Cshake256_Final(wc_Cshake* cshake, byte* out, word32 outLen)
3685
{
3686
    return CshakeFinal(cshake, out, outLen);
3687
}
3688
3689
/* Copy the state of a cSHAKE256 operation, allowing it to be finalized more
3690
 * than once (for example over a common message prefix). dst must already be
3691
 * an initialized wc_Cshake.
3692
 *
3693
 * @param [in]  src  wc_Cshake object to copy from.
3694
 * @param [out] dst  wc_Cshake object to copy into.
3695
 *
3696
 * @return  0 on success.
3697
 * @return  BAD_FUNC_ARG when src or dst is NULL.
3698
 */
3699
int wc_Cshake256_Copy(wc_Cshake* src, wc_Cshake* dst)
3700
{
3701
    return CshakeCopy(src, dst);
3702
}
3703
3704
/* Dispose of any dynamically allocated data from a cSHAKE256 operation.
3705
 *
3706
 * @param [in,out] cshake  wc_Cshake object to free. May be NULL.
3707
 */
3708
void wc_Cshake256_Free(wc_Cshake* cshake)
3709
{
3710
    if (cshake != NULL) {
3711
        wc_Sha3Free(&cshake->shake);
3712
    }
3713
}
3714
3715
/* One-shot cSHAKE256 over a single message. See wc_Cshake128() for details.
3716
 *
3717
 * @param [in]  name       Function-name string, or NULL when nameLen is 0.
3718
 * @param [in]  nameLen    Length of name in bytes.
3719
 * @param [in]  custom     Customization string, or NULL when customLen is 0.
3720
 * @param [in]  customLen  Length of the customization string in bytes.
3721
 * @param [in]  in         Message bytes, or NULL when inLen is 0.
3722
 * @param [in]  inLen      Length of the message in bytes.
3723
 * @param [out] out        Buffer to hold the output.
3724
 * @param [in]  outLen     Number of output bytes to produce.
3725
 *
3726
 * @return  0 on success.
3727
 * @return  Negative error code on failure.
3728
 */
3729
int wc_Cshake256(const byte* name, word32 nameLen, const byte* custom,
3730
    word32 customLen, const byte* in, word32 inLen, byte* out, word32 outLen)
3731
{
3732
    int ret = 0;
3733
    /* Heap-allocate the state on small-stack builds (it is ~400 bytes). */
3734
    WC_DECLARE_VAR(cshake, wc_Cshake, 1, NULL);
3735
3736
    WC_ALLOC_VAR_EX(cshake, wc_Cshake, 1, NULL, DYNAMIC_TYPE_TMP_BUFFER,
3737
        ret = MEMORY_E);
3738
3739
    if (ret == 0) {
3740
        ret = wc_InitCshake256(cshake, name, nameLen, custom, customLen, NULL,
3741
            INVALID_DEVID);
3742
    }
3743
    if (ret == 0) {
3744
        ret = wc_Cshake256_Update(cshake, in, inLen);
3745
    }
3746
    if (ret == 0) {
3747
        ret = wc_Cshake256_Final(cshake, out, outLen);
3748
    }
3749
    /* wc_Cshake256_Free tolerates a NULL pointer (allocation failure). */
3750
    wc_Cshake256_Free(cshake);
3751
    WC_FREE_VAR_EX(cshake, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3752
3753
    return ret;
3754
}
3755
#endif /* WOLFSSL_CSHAKE256 */
3756
3757
#endif /* (WOLFSSL_KMAC || WOLFSSL_CSHAKE) && WC_SHA3_SW_KECCAK */
3758
3759
#endif /* WOLFSSL_SHA3 */