Coverage Report

Created: 2026-09-27 06:31

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
/* Mask each cell to an octet: where CHAR_BIT != 8 a cell can hold more than an
835
 * octet and would bleed into the neighbouring lane bits.  Matches
836
 * readUnalignedWord32/64() in misc.c.  No-op where a byte is an octet. */
837
static WC_INLINE word64 Load64Unaligned(const unsigned char *a)
838
{
839
    return ((word64)(a[0] & 0xFF) <<  0) |
840
           ((word64)(a[1] & 0xFF) <<  8) |
841
           ((word64)(a[2] & 0xFF) << 16) |
842
           ((word64)(a[3] & 0xFF) << 24) |
843
           ((word64)(a[4] & 0xFF) << 32) |
844
           ((word64)(a[5] & 0xFF) << 40) |
845
           ((word64)(a[6] & 0xFF) << 48) |
846
           ((word64)(a[7] & 0xFF) << 56);
847
}
848
849
/* Convert the array of bytes, in little-endian order, to a 64-bit integer.
850
 *
851
 * a  Array of bytes.
852
 * returns a 64-bit integer.
853
 */
854
static word64 Load64BitLittleEndian(const byte* a)
855
{
856
    word64 n = 0;
857
    int i;
858
859
    /* Masked as in Load64Unaligned() above. */
860
    for (i = 0; i < 8; i++)
861
        n |= (word64)(a[i] & 0xFF) << (8 * i);
862
863
    return n;
864
}
865
#elif defined(WC_SHA3_FAULT_HARDEN)
866
static WC_INLINE word64 Load64Unaligned(const unsigned char *a) {
867
    return readUnalignedWord64(a);
868
}
869
870
/* Convert the array of bytes, in little-endian order, to a 64-bit integer.
871
 *
872
 * a  Array of bytes.
873
 * returns a 64-bit integer.
874
 */
875
static word64 Load64BitLittleEndian(const byte* a)
876
{
877
    return Load64Unaligned(a);
878
}
879
#endif
880
881
/* Initialize the state for a SHA3-224 hash operation.
882
 *
883
 * sha3   wc_Sha3 object holding state.
884
 * returns 0 on success.
885
 */
886
887
static int InitSha3(wc_Sha3* sha3)
888
0
{
889
0
    int i;
890
891
0
    for (i = 0; i < 25; i++)
892
0
        sha3->s[i] = 0;
893
0
    XMEMSET(sha3->t, 0, sizeof(sha3->t));
894
0
    sha3->i = 0;
895
#ifdef WOLFSSL_HASH_FLAGS
896
    sha3->flags = 0;
897
#endif
898
#ifdef WOLF_CRYPTO_CB
899
    /* Cached hash variant is tied to sponge state; clear it whenever the
900
     * state is reset so reuse for a different SHA3 variant dispatches
901
     * correctly through the crypto callback. */
902
    sha3->hashType = WC_HASH_TYPE_NONE;
903
#endif
904
905
#ifdef USE_INTEL_SPEEDUP
906
    {
907
        int cpuid_flags_were_updated = cpuid_get_flags_ex(&cpuid_flags);
908
#ifdef WC_C_DYNAMIC_FALLBACK
909
        (void)cpuid_flags_were_updated;
910
        if (! CAN_SAVE_VECTOR_REGISTERS()) {
911
            SHA3_BLOCK = BlockSha3;
912
            SHA3_BLOCK_N = NULL;
913
        }
914
        else
915
#else
916
        if ((! cpuid_flags_were_updated) && (SHA3_BLOCK != NULL)) {
917
        }
918
        else
919
#endif
920
        /* See the selection comment above: AVX2 on Intel, otherwise BMI2. */
921
        if (SHA3_USE_AVX2(cpuid_flags)) {
922
            SHA3_BLOCK = sha3_block_avx2;
923
            SHA3_BLOCK_N = sha3_block_n_avx2;
924
        }
925
        else if (IS_INTEL_BMI1(cpuid_flags) && IS_INTEL_BMI2(cpuid_flags)) {
926
            SHA3_BLOCK = sha3_block_bmi2;
927
            SHA3_BLOCK_N = sha3_block_n_bmi2;
928
        }
929
        else {
930
            SHA3_BLOCK = BlockSha3;
931
            SHA3_BLOCK_N = NULL;
932
        }
933
    }
934
#define SHA3_FUNC_PTR
935
#endif /* USE_INTEL_SPEEDUP */
936
#if defined(__aarch64__) && defined(WOLFSSL_ARMASM)
937
    {
938
        int cpuid_flags_were_updated = cpuid_get_flags_ex(&cpuid_flags);
939
        if ((! cpuid_flags_were_updated) && (SHA3_BLOCK != NULL)) {
940
        }
941
        else
942
    #ifdef WOLFSSL_ARMASM_CRYPTO_SHA3
943
        if (IS_AARCH64_SHA3(cpuid_flags)) {
944
            SHA3_BLOCK = BlockSha3_crypto;
945
            SHA3_BLOCK_N = NULL;
946
        }
947
        else
948
    #endif
949
        {
950
            SHA3_BLOCK = BlockSha3_base;
951
            SHA3_BLOCK_N = NULL;
952
        }
953
    }
954
#define SHA3_FUNC_PTR
955
#endif
956
957
0
    return 0;
958
0
}
959
960
#if defined(__aarch64__) && defined(WOLFSSL_ARMASM)
961
void BlockSha3(word64* s)
962
{
963
    (*SHA3_BLOCK)(s);
964
}
965
#endif
966
967
/* Update the SHA-3 hash state with message data.
968
 *
969
 * sha3  wc_Sha3 object holding state.
970
 * data  Message data to be hashed.
971
 * len   Length of the message data.
972
 * p     Number of 64-bit numbers in a block of data to process.
973
 * returns 0 on success.
974
 */
975
static int Sha3Update(wc_Sha3* sha3, const byte* data, word32 len, word32 p)
976
0
{
977
0
    word32 i;
978
0
    word32 blocks;
979
0
    int ret = 0;
980
#ifdef WC_SHA3_FAULT_HARDEN
981
    word32 check = 0;
982
    word32 total_check = 0;
983
#endif
984
#ifdef USE_INTEL_SPEEDUP
985
#ifdef WC_C_DYNAMIC_FALLBACK
986
    void (*sha3_block)(word64 *s) = SHA3_BLOCK;
987
    void (*sha3_block_n)(word64 *s, const byte* data, word32 n,
988
        word64 c) = SHA3_BLOCK_N;
989
#endif
990
#endif /* USE_INTEL_SPEEDUP */
991
992
0
    if ((p < WC_SHA3_512_COUNT) || (p > WC_SHA3_128_COUNT))
993
0
        return BAD_STATE_E;
994
995
#ifdef USE_INTEL_SPEEDUP
996
    if (SHA3_BLOCK_VREGS(sha3_block)) {
997
        ret = SAVE_VECTOR_REGISTERS2();
998
        if (ret != 0) {
999
#ifdef WC_C_DYNAMIC_FALLBACK
1000
            sha3_block = BlockSha3;
1001
            sha3_block_n = NULL;
1002
            ret = 0;
1003
#else
1004
            return ret;
1005
#endif
1006
        }
1007
    }
1008
#endif /* USE_INTEL_SPEEDUP */
1009
1010
0
    if (sha3->i > 0) {
1011
0
        byte *t;
1012
0
        word32 l;
1013
0
        if (p * 8 < sha3->i) {
1014
0
            ret = BAD_STATE_E;
1015
0
            goto out;
1016
0
        }
1017
0
        l = (p * 8 - sha3->i);
1018
0
        if (l > len) {
1019
0
            l = len;
1020
0
        }
1021
1022
0
        t = &sha3->t[sha3->i];
1023
0
        for (i = 0; i < l; i++) {
1024
0
            t[i] = data[i];
1025
    #ifdef WC_SHA3_FAULT_HARDEN
1026
            check++;
1027
    #endif
1028
0
        }
1029
    #ifdef WC_SHA3_FAULT_HARDEN
1030
        if (check != l) {
1031
            ret = BAD_COND_E;
1032
            goto out;
1033
        }
1034
        total_check += l;
1035
    #endif
1036
0
        data += i;
1037
0
        len -= i;
1038
0
        sha3->i += i;
1039
1040
0
        if (sha3->i == p * 8) {
1041
0
    #if !defined(BIG_ENDIAN_ORDER) && !defined(WC_SHA3_FAULT_HARDEN) && \
1042
0
        !defined(WOLFSSL_WIDE_BYTE)
1043
0
            xorbuf(sha3->s, sha3->t, (word32)(p * 8));
1044
    #else
1045
            for (i = 0; i < p; i++) {
1046
                sha3->s[i] ^= Load64BitLittleEndian(sha3->t + 8 * i);
1047
            #ifdef WC_SHA3_FAULT_HARDEN
1048
                check++;
1049
            #endif
1050
            }
1051
        #ifdef WC_SHA3_FAULT_HARDEN
1052
            if (check != p + l) {
1053
                ret = BAD_COND_E;
1054
                goto out;
1055
            }
1056
            total_check += p;
1057
        #endif
1058
    #endif
1059
        #ifdef SHA3_FUNC_PTR
1060
            (*sha3_block)(sha3->s);
1061
        #else
1062
0
            BlockSha3(sha3->s);
1063
0
        #endif
1064
0
            sha3->i = 0;
1065
0
        }
1066
0
    }
1067
0
    blocks = len / (p * 8U);
1068
    #ifdef SHA3_FUNC_PTR
1069
    if ((sha3_block_n != NULL) && (blocks > 0)) {
1070
        (*sha3_block_n)(sha3->s, data, blocks, p * 8U);
1071
        len -= blocks * (p * 8U);
1072
        data += blocks * (p * 8U);
1073
        blocks = 0;
1074
    }
1075
    #endif
1076
#ifdef WC_SHA3_FAULT_HARDEN
1077
    total_check += blocks * p;
1078
#endif
1079
0
    for (; blocks > 0; blocks--) {
1080
0
#if !defined(BIG_ENDIAN_ORDER) && !defined(WC_SHA3_FAULT_HARDEN) && \
1081
0
    !defined(WOLFSSL_WIDE_BYTE)
1082
0
        xorbuf(sha3->s, data, (word32)(p * 8));
1083
#else
1084
        for (i = 0; i < p; i++) {
1085
            sha3->s[i] ^= Load64Unaligned(data + 8 * i);
1086
        #ifdef WC_SHA3_FAULT_HARDEN
1087
            check++;
1088
        #endif
1089
        }
1090
    #ifdef WC_SHA3_FAULT_HARDEN
1091
        if (check != total_check - ((blocks - 1) * p)) {
1092
            ret = BAD_COND_E;
1093
            goto out;
1094
        }
1095
    #endif
1096
#endif
1097
    #ifdef SHA3_FUNC_PTR
1098
        (*sha3_block)(sha3->s);
1099
    #else
1100
0
        BlockSha3(sha3->s);
1101
0
    #endif
1102
0
        len -= p * 8U;
1103
0
        data += p * 8U;
1104
0
    }
1105
#ifdef WC_SHA3_FAULT_HARDEN
1106
    if (check != total_check) {
1107
        ret = BAD_COND_E;
1108
        goto out;
1109
    }
1110
#endif
1111
1112
0
out:
1113
1114
#ifdef USE_INTEL_SPEEDUP
1115
    if (SHA3_BLOCK_VREGS(sha3_block)) {
1116
        RESTORE_VECTOR_REGISTERS();
1117
    }
1118
#endif
1119
1120
0
    if (ret == 0) {
1121
0
        if (len > 0) {
1122
0
            XMEMCPY(sha3->t, data, len);
1123
0
        }
1124
0
        sha3->i += len;
1125
0
    }
1126
1127
0
    return ret;
1128
0
}
1129
1130
/* Calculate the SHA-3 hash based on all the message data seen.
1131
 *
1132
 * sha3  wc_Sha3 object holding state.
1133
 * hash  Buffer to hold the hash result.
1134
 * p     Number of 64-bit numbers in a block of data to process.
1135
 * len   Number of bytes in output.
1136
 * returns 0 on success.
1137
 */
1138
#ifdef WOLFSSL_WIDE_BYTE
1139
/* Squeeze len output bytes from the Keccak state, extracting each octet from
1140
 * the 64-bit lanes (little-endian within a lane).  Used where a C 'byte' is
1141
 * wider than 8 bits (CHAR_BIT != 8) so the state cannot be copied as an octet
1142
 * stream. */
1143
static void Sha3SqueezeBytes(byte* out, const word64* s, word32 len)
1144
{
1145
    word32 k;
1146
    for (k = 0; k < len; k++) {
1147
        out[k] = (byte)((s[k >> 3] >> (8 * (k & 7))) & 0xFF);
1148
    }
1149
}
1150
#endif
1151
1152
static int Sha3Final(wc_Sha3* sha3, byte padChar, byte* hash, word32 p, word32 l)
1153
0
{
1154
0
    word32 rate = p * 8U;
1155
0
    word32 j;
1156
#if defined(BIG_ENDIAN_ORDER) || defined(WC_SHA3_FAULT_HARDEN) || \
1157
    defined(WOLFSSL_WIDE_BYTE)
1158
    word32 i;
1159
#endif
1160
#ifdef WC_SHA3_FAULT_HARDEN
1161
    word32 check = 0;
1162
#endif
1163
#if defined(WC_C_DYNAMIC_FALLBACK) && defined(USE_INTEL_SPEEDUP)
1164
    void (*sha3_block)(word64 *s) = SHA3_BLOCK;
1165
#endif
1166
1167
0
    if ((p < WC_SHA3_512_COUNT) || (p > WC_SHA3_128_COUNT))
1168
0
        return BAD_STATE_E;
1169
0
    if (sha3->i >= rate)
1170
0
        return BAD_STATE_E;
1171
1172
0
#if !defined(BIG_ENDIAN_ORDER) && !defined(WC_SHA3_FAULT_HARDEN) && \
1173
0
    !defined(WOLFSSL_WIDE_BYTE)
1174
0
    xorbuf(sha3->s, sha3->t, sha3->i);
1175
#ifdef WOLFSSL_HASH_FLAGS
1176
    if ((p == WC_SHA3_256_COUNT) && (sha3->flags & WC_HASH_SHA3_KECCAK256)) {
1177
        padChar = 0x01;
1178
    }
1179
#endif
1180
0
    ((byte*)sha3->s)[sha3->i ] ^= padChar;
1181
0
    ((byte*)sha3->s)[rate - 1] ^= 0x80;
1182
#else
1183
    sha3->t[rate - 1]  = 0x00;
1184
#ifdef WOLFSSL_HASH_FLAGS
1185
    if ((p == WC_SHA3_256_COUNT) && (sha3->flags & WC_HASH_SHA3_KECCAK256)) {
1186
        padChar = 0x01;
1187
    }
1188
#endif
1189
    sha3->t[sha3->i ]  = padChar;
1190
    sha3->t[rate - 1] |= 0x80;
1191
    if (rate - 1 > sha3->i + 1) {
1192
        XMEMSET(sha3->t + sha3->i + 1, 0, rate - 1U - (sha3->i + 1U));
1193
    }
1194
    for (i = 0; i < p; i++) {
1195
        sha3->s[i] ^= Load64BitLittleEndian(sha3->t + 8 * i);
1196
    #ifdef WC_SHA3_FAULT_HARDEN
1197
        check++;
1198
    #endif
1199
    }
1200
#ifdef WC_SHA3_FAULT_HARDEN
1201
    if (check != p) {
1202
        return BAD_COND_E;
1203
    }
1204
#endif
1205
#endif
1206
1207
#ifdef USE_INTEL_SPEEDUP
1208
    if (SHA3_BLOCK_VREGS(sha3_block)) {
1209
        int ret = SAVE_VECTOR_REGISTERS2();
1210
        if (ret != 0) {
1211
#ifdef WC_C_DYNAMIC_FALLBACK
1212
            sha3_block = BlockSha3;
1213
#else
1214
            return ret;
1215
#endif
1216
        }
1217
    }
1218
#endif
1219
1220
0
    for (j = 0; l - j >= rate; j += rate) {
1221
    #ifdef SHA3_FUNC_PTR
1222
        (*sha3_block)(sha3->s);
1223
    #else
1224
0
        BlockSha3(sha3->s);
1225
0
    #endif
1226
    #if defined(BIG_ENDIAN_ORDER)
1227
        ByteReverseWords64((word64*)(hash + j), sha3->s, rate);
1228
    #elif defined(WOLFSSL_WIDE_BYTE)
1229
        Sha3SqueezeBytes(hash + j, sha3->s, rate);
1230
    #else
1231
0
        XMEMCPY(hash + j, sha3->s, rate);
1232
0
    #endif
1233
0
    }
1234
0
    if (j != l) {
1235
    #ifdef SHA3_FUNC_PTR
1236
        (*sha3_block)(sha3->s);
1237
    #else
1238
0
        BlockSha3(sha3->s);
1239
0
    #endif
1240
    #if defined(BIG_ENDIAN_ORDER)
1241
        ByteReverseWords64(sha3->s, sha3->s, rate);
1242
        XMEMCPY(hash + j, sha3->s, l - j);
1243
    #elif defined(WOLFSSL_WIDE_BYTE)
1244
        Sha3SqueezeBytes(hash + j, sha3->s, l - j);
1245
    #else
1246
0
        XMEMCPY(hash + j, sha3->s, l - j);
1247
0
    #endif
1248
0
    }
1249
#ifdef USE_INTEL_SPEEDUP
1250
    if (SHA3_BLOCK_VREGS(sha3_block)) {
1251
        RESTORE_VECTOR_REGISTERS();
1252
    }
1253
#endif
1254
1255
0
    return 0;
1256
0
}
1257
#endif /* WC_SHA3_SW_KECCAK */
1258
#if defined(STM32_HASH_SHA3)
1259
1260
/* Supports CubeMX HAL or Standard Peripheral Library */
1261
1262
static int wc_InitSha3(wc_Sha3* sha3, void* heap, int devId)
1263
{
1264
    if (sha3 == NULL)
1265
        return BAD_FUNC_ARG;
1266
1267
    (void)devId;
1268
    (void)heap;
1269
1270
    XMEMSET(sha3, 0, sizeof(wc_Sha3));
1271
    wc_Stm32_Hash_Init(&sha3->stmCtx);
1272
    return 0;
1273
}
1274
1275
static int Stm32GetAlgo(word32 p)
1276
{
1277
    switch(p) {
1278
        case WC_SHA3_224_COUNT:
1279
            return HASH_ALGOSELECTION_SHA3_224;
1280
        case WC_SHA3_256_COUNT:
1281
            return HASH_ALGOSELECTION_SHA3_256;
1282
        case WC_SHA3_384_COUNT:
1283
            return HASH_ALGOSELECTION_SHA3_384;
1284
        case WC_SHA3_512_COUNT:
1285
            return HASH_ALGOSELECTION_SHA3_512;
1286
    }
1287
    /* Should never get here */
1288
    return WC_SHA3_224_COUNT;
1289
}
1290
1291
static int wc_Sha3Update(wc_Sha3* sha3, const byte* data, word32 len, word32 p)
1292
{
1293
    int ret = 0;
1294
1295
    if (sha3 == NULL) {
1296
        return BAD_FUNC_ARG;
1297
    }
1298
    if (data == NULL && len == 0) {
1299
        /* valid, but do nothing */
1300
        return 0;
1301
    }
1302
    if (data == NULL) {
1303
        return BAD_FUNC_ARG;
1304
    }
1305
1306
    ret = wolfSSL_CryptHwMutexLock();
1307
    if (ret == 0) {
1308
        ret = wc_Stm32_Hash_Update(&sha3->stmCtx, Stm32GetAlgo(p), data, len,
1309
            p * 8);
1310
        wolfSSL_CryptHwMutexUnLock();
1311
    }
1312
    return ret;
1313
}
1314
1315
static int wc_Sha3Final(wc_Sha3* sha3, byte* hash, word32 p, word32 len)
1316
{
1317
    int ret = 0;
1318
1319
    if (sha3 == NULL || hash == NULL) {
1320
        return BAD_FUNC_ARG;
1321
    }
1322
1323
    ret = wolfSSL_CryptHwMutexLock();
1324
    if (ret == 0) {
1325
        ret = wc_Stm32_Hash_Final(&sha3->stmCtx, Stm32GetAlgo(p), hash, len);
1326
        wolfSSL_CryptHwMutexUnLock();
1327
    }
1328
1329
    (void)wc_InitSha3(sha3, NULL, 0); /* reset state */
1330
1331
    return ret;
1332
}
1333
#elif defined(PSOC6_HASH_SHA3)
1334
1335
static int wc_InitSha3(wc_Sha3* sha3, void* heap, int devId)
1336
{
1337
    int ret;
1338
    if (sha3 == NULL) {
1339
        return BAD_FUNC_ARG;
1340
    }
1341
    (void)devId;
1342
    (void)heap;
1343
1344
    /* Lock the mutex to perform crypto operations */
1345
    ret = wolfSSL_CryptHwMutexLock();
1346
    if (ret == 0) {
1347
        /* Initialize hash state for SHA-3 operation */
1348
        ret = wc_Psoc6_Sha3_Init(sha3);
1349
        /* Release the lock */
1350
        wolfSSL_CryptHwMutexUnLock();
1351
    }
1352
1353
    return ret;
1354
}
1355
1356
static int wc_Sha3Update(wc_Sha3* sha3, const byte* data, word32 len, word32 p)
1357
{
1358
    int ret;
1359
1360
    if (sha3 == NULL || (data == NULL && len > 0)) {
1361
        return BAD_FUNC_ARG;
1362
    }
1363
1364
    if (data == NULL) {
1365
        /* len is 0 here: valid, but do nothing */
1366
        return 0;
1367
    }
1368
1369
    /* Lock the mutex to perform crypto operations */
1370
    ret = wolfSSL_CryptHwMutexLock();
1371
    if (ret == 0) {
1372
        /* Perform SHA3 on the input data and update the hash state */
1373
        ret = wc_Psoc6_Sha3_Update(sha3, data, len, p);
1374
        /* Release the lock */
1375
        wolfSSL_CryptHwMutexUnLock();
1376
    }
1377
1378
    return ret;
1379
}
1380
1381
static int wc_Sha3Final(wc_Sha3* sha3, byte* hash, word32 p, word32 len)
1382
{
1383
    int ret;
1384
1385
    if (sha3 == NULL || hash == NULL) {
1386
        return BAD_FUNC_ARG;
1387
    }
1388
1389
    /* Lock the mutex to perform crypto operations */
1390
    ret = wolfSSL_CryptHwMutexLock();
1391
    if (ret == 0) {
1392
        /* Finalize SHA3 operations and produce digest */
1393
        ret = wc_Psoc6_Sha3_Final(sha3, 0x06, hash, p, len);
1394
        if (ret == 0) {
1395
            /* Initialize hash state for SHA-3 operation */
1396
            ret = wc_Psoc6_Sha3_Init(sha3);
1397
        }
1398
        /* Release the lock */
1399
        wolfSSL_CryptHwMutexUnLock();
1400
    }
1401
1402
    return ret;
1403
}
1404
1405
#else
1406
1407
/* Initialize the state for a SHA-3 hash operation.
1408
 *
1409
 * sha3   wc_Sha3 object holding state.
1410
 * heap   Heap reference for dynamic memory allocation. (Used in async ops.)
1411
 * devId  Device identifier for asynchronous operation.
1412
 * returns 0 on success.
1413
 */
1414
static int wc_InitSha3(wc_Sha3* sha3, void* heap, int devId)
1415
0
{
1416
0
    int ret = 0;
1417
1418
0
    if (sha3 == NULL)
1419
0
        return BAD_FUNC_ARG;
1420
1421
0
    sha3->heap = heap;
1422
0
    ret = InitSha3(sha3);
1423
0
    if (ret != 0)
1424
0
        return ret;
1425
1426
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_SHA3)
1427
    ret = wolfAsync_DevCtxInit(&sha3->asyncDev,
1428
                        WOLFSSL_ASYNC_MARKER_SHA3, sha3->heap, devId);
1429
#endif
1430
#if defined(WOLF_CRYPTO_CB)
1431
    sha3->devId = devId;
1432
    sha3->devCtx = NULL;
1433
    /* Set to none to determine the hash type later */
1434
    /* in the update/final functions based on the p value */
1435
    sha3->hashType = WC_HASH_TYPE_NONE;
1436
#endif
1437
0
    (void)devId;
1438
1439
0
    return ret;
1440
0
}
1441
1442
#if !(defined(WOLFSSL_NOSHA3_224) && defined(WOLFSSL_NOSHA3_256) && \
1443
      defined(WOLFSSL_NOSHA3_384) && defined(WOLFSSL_NOSHA3_512))
1444
/* Update the SHA-3 hash state with message data.
1445
 *
1446
 * sha3  wc_Sha3 object holding state.
1447
 * data  Message data to be hashed.
1448
 * len   Length of the message data.
1449
 * p     Number of 64-bit numbers in a block of data to process.
1450
 * returns 0 on success.
1451
 */
1452
static int wc_Sha3Update(wc_Sha3* sha3, const byte* data, word32 len, word32 p)
1453
0
{
1454
0
    int ret;
1455
1456
0
    if (sha3 == NULL) {
1457
0
        return BAD_FUNC_ARG;
1458
0
    }
1459
1460
0
    if (data == NULL && len == 0) {
1461
        /* valid, but do nothing */
1462
0
        return 0;
1463
0
    }
1464
1465
0
    if (data == NULL) {
1466
0
        return BAD_FUNC_ARG;
1467
0
    }
1468
1469
#ifdef WOLF_CRYPTO_CB
1470
    #ifndef WOLF_CRYPTO_CB_FIND
1471
    if (sha3->devId != INVALID_DEVID)
1472
    #endif
1473
    {
1474
        /* If the hash type is not set, determine it based on the p value */
1475
        /* We can skip the switch statement if the hash type set already */
1476
        if (sha3->hashType == WC_HASH_TYPE_NONE) {
1477
            switch (p) {
1478
                case WC_SHA3_224_COUNT:
1479
                    sha3->hashType = WC_HASH_TYPE_SHA3_224; break;
1480
                case WC_SHA3_256_COUNT:
1481
                    sha3->hashType = WC_HASH_TYPE_SHA3_256; break;
1482
                case WC_SHA3_384_COUNT:
1483
                    sha3->hashType = WC_HASH_TYPE_SHA3_384; break;
1484
                case WC_SHA3_512_COUNT:
1485
                    sha3->hashType = WC_HASH_TYPE_SHA3_512; break;
1486
                default: return BAD_FUNC_ARG;
1487
            }
1488
        }
1489
        ret = wc_CryptoCb_Sha3Hash(sha3, sha3->hashType, data, len, NULL);
1490
        if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE))
1491
            return ret;
1492
        /* fall-through when unavailable */
1493
    }
1494
#endif
1495
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_SHA3)
1496
    if (sha3->asyncDev.marker == WOLFSSL_ASYNC_MARKER_SHA3) {
1497
    #if defined(HAVE_INTEL_QA) && defined(QAT_V2)
1498
        /* QAT only supports SHA3_256 */
1499
        if (p == WC_SHA3_256_COUNT) {
1500
            ret = IntelQaSymSha3(&sha3->asyncDev, NULL, data, len);
1501
            if (ret != WC_NO_ERR_TRACE(NOT_COMPILED_IN))
1502
                return ret;
1503
            /* fall-through when unavailable */
1504
        }
1505
    #endif
1506
    }
1507
#endif /* WOLFSSL_ASYNC_CRYPT */
1508
1509
0
    ret = Sha3Update(sha3, data, len, p);
1510
1511
0
    return ret;
1512
0
}
1513
1514
/* Calculate the SHA-3 hash based on all the message data seen.
1515
 *
1516
 * sha3  wc_Sha3 object holding state.
1517
 * hash  Buffer to hold the hash result.
1518
 * p     Number of 64-bit numbers in a block of data to process.
1519
 * len   Number of bytes in output.
1520
 * returns 0 on success.
1521
 */
1522
static int wc_Sha3Final(wc_Sha3* sha3, byte* hash, word32 p, word32 len)
1523
0
{
1524
0
    int ret;
1525
1526
0
    if (sha3 == NULL || hash == NULL) {
1527
0
        return BAD_FUNC_ARG;
1528
0
    }
1529
1530
#ifdef WOLF_CRYPTO_CB
1531
    #ifndef WOLF_CRYPTO_CB_FIND
1532
    if (sha3->devId != INVALID_DEVID)
1533
    #endif
1534
    {
1535
        /* If the hash type is not set, determine it based on the p value */
1536
        /* We can skip the switch statement if the hash type is set already */
1537
        if (sha3->hashType == WC_HASH_TYPE_NONE) {
1538
            switch (p) {
1539
                case WC_SHA3_224_COUNT:
1540
                    sha3->hashType = WC_HASH_TYPE_SHA3_224; break;
1541
                case WC_SHA3_256_COUNT:
1542
                    sha3->hashType = WC_HASH_TYPE_SHA3_256; break;
1543
                case WC_SHA3_384_COUNT:
1544
                    sha3->hashType = WC_HASH_TYPE_SHA3_384; break;
1545
                case WC_SHA3_512_COUNT:
1546
                    sha3->hashType = WC_HASH_TYPE_SHA3_512; break;
1547
                default: return BAD_FUNC_ARG;
1548
            }
1549
        }
1550
        ret = wc_CryptoCb_Sha3Hash(sha3, sha3->hashType, NULL, 0, hash);
1551
        if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE))
1552
            return ret;
1553
        /* fall-through when unavailable */
1554
    }
1555
#endif
1556
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_SHA3)
1557
    if (sha3->asyncDev.marker == WOLFSSL_ASYNC_MARKER_SHA3) {
1558
    #if defined(HAVE_INTEL_QA) && defined(QAT_V2)
1559
        /* QAT only supports SHA3_256 */
1560
        /* QAT SHA-3 only supported on v2 (8970 or later cards) */
1561
        if (len == WC_SHA3_256_DIGEST_SIZE) {
1562
            ret = IntelQaSymSha3(&sha3->asyncDev, hash, NULL, len);
1563
            if (ret != WC_NO_ERR_TRACE(NOT_COMPILED_IN))
1564
                return ret;
1565
            /* fall-through when unavailable */
1566
        }
1567
    #endif
1568
    }
1569
#endif /* WOLFSSL_ASYNC_CRYPT */
1570
1571
0
    ret = Sha3Final(sha3, 0x06, hash, p, (word32)len);
1572
0
    if (ret != 0)
1573
0
        return ret;
1574
1575
0
    return InitSha3(sha3);  /* reset state */
1576
0
}
1577
#endif
1578
#endif
1579
1580
/* Dispose of any dynamically allocated data from the SHA3-384 operation.
1581
 * (Required for async ops.)
1582
 *
1583
 * sha3  wc_Sha3 object holding state.
1584
 * returns 0 on success.
1585
 */
1586
static void wc_Sha3Free(wc_Sha3* sha3)
1587
0
{
1588
#if defined(WOLF_CRYPTO_CB) && defined(WOLF_CRYPTO_CB_FREE)
1589
    int ret = 0;
1590
#endif
1591
1592
0
    (void)sha3;
1593
1594
#if defined(WOLF_CRYPTO_CB) && defined(WOLF_CRYPTO_CB_FREE)
1595
    if (sha3 == NULL)
1596
        return;
1597
1598
    #ifndef WOLF_CRYPTO_CB_FIND
1599
    if (sha3->devId != INVALID_DEVID)
1600
    #endif
1601
    {
1602
        ret = wc_CryptoCb_Free(sha3->devId, WC_ALGO_TYPE_HASH,
1603
                         sha3->hashType, 0, (void*)sha3);
1604
        /* If they want the standard free, they can call it themselves */
1605
        /* via their callback setting devId to INVALID_DEVID */
1606
        /* otherwise assume the callback handled it */
1607
        if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE))
1608
            return;
1609
        /* fall-through when unavailable */
1610
    }
1611
1612
    /* silence compiler warning */
1613
    (void)ret;
1614
1615
#endif /* WOLF_CRYPTO_CB && WOLF_CRYPTO_CB_FREE */
1616
1617
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_SHA3)
1618
    if (sha3 == NULL)
1619
        return;
1620
1621
    wolfAsync_DevCtxFree(&sha3->asyncDev, WOLFSSL_ASYNC_MARKER_SHA3);
1622
#endif /* WOLFSSL_ASYNC_CRYPT */
1623
1624
#if defined(PSOC6_HASH_SHA3)
1625
    wc_Psoc6_Sha_Free();
1626
#endif
1627
0
}
1628
1629
/* Reset a SHA-3/SHAKE context to its freshly initialized state, reusing its
1630
 * existing heap hint and device association.  Like the Final functions,
1631
 * Reset does not destroy sensitive internal state; use the matching Free
1632
 * function for teardown at end of life.
1633
 */
1634
static int wc_Sha3Reset(wc_Sha3* sha3)
1635
0
{
1636
0
    if (sha3 == NULL)
1637
0
        return BAD_FUNC_ARG;
1638
1639
0
#if !defined(WOLFSSL_HASH_KEEP) && !defined(STM32_HASH_SHA3) && \
1640
0
    !defined(PSOC6_HASH_SHA3)
1641
#ifdef WOLF_CRYPTO_CB
1642
    /* A device may hang state off devCtx that InitSha3() cannot restart.
1643
     * Free and re-init so the callback gets its teardown and setup. */
1644
    #ifndef WOLF_CRYPTO_CB_FIND
1645
    if (sha3->devId != INVALID_DEVID)
1646
    #endif
1647
    {
1648
        void* heap = sha3->heap;
1649
        int devId = sha3->devId;
1650
        wc_Sha3Free(sha3);
1651
        return wc_InitSha3(sha3, heap, devId);
1652
    }
1653
#endif
1654
    /* InitSha3() reinitializes the sponge and block-dispatch state in place,
1655
     * touching neither the heap hint nor the device association. */
1656
0
    return InitSha3(sha3);
1657
#else
1658
    {
1659
#if defined(PSOC6_HASH_SHA3)
1660
        /* The PSOC6 wc_Sha3 carries no heap hint or devId, and its
1661
         * wc_InitSha3() ignores both. */
1662
        void *heap = NULL;
1663
        int devId = INVALID_DEVID;
1664
#else
1665
        void *heap = sha3->heap;
1666
#ifdef WOLF_CRYPTO_CB
1667
        int devId = sha3->devId;
1668
#else
1669
        int devId = INVALID_DEVID;
1670
#endif
1671
#endif /* PSOC6_HASH_SHA3 */
1672
        wc_Sha3Free(sha3);
1673
        return wc_InitSha3(sha3, heap, devId);
1674
    }
1675
#endif /* !ASYNC && !HASH_KEEP && !STM32 && !PSOC6 */
1676
0
}
1677
1678
/* Copy the state of the SHA3 operation.
1679
 *
1680
 * src  wc_Sha3 object holding state top copy.
1681
 * dst  wc_Sha3 object to copy into.
1682
 * returns 0 on success.
1683
 */
1684
static int wc_Sha3Copy(wc_Sha3* src, wc_Sha3* dst)
1685
0
{
1686
0
    int ret = 0;
1687
1688
0
    if (src == NULL || dst == NULL)
1689
0
        return BAD_FUNC_ARG;
1690
1691
#if defined(WOLF_CRYPTO_CB) && defined(WOLF_CRYPTO_CB_COPY)
1692
    #ifndef WOLF_CRYPTO_CB_FIND
1693
    if (src->devId != INVALID_DEVID)
1694
    #endif
1695
    {
1696
        /* Cast the source and destination to be void to keep the abstraction */
1697
        ret = wc_CryptoCb_Copy(src->devId, WC_ALGO_TYPE_HASH,
1698
                               src->hashType, (void*)src, (void*)dst);
1699
        if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE))
1700
            return ret;
1701
        /* fall-through when unavailable */
1702
    }
1703
    ret = 0; /* Reset ret to 0 to avoid returning the callback error code */
1704
#endif /* WOLF_CRYPTO_CB && WOLF_CRYPTO_CB_COPY */
1705
1706
    /* Free dst resources before copy to prevent memory leaks (e.g.,
1707
     * hardware contexts). XMEMCPY overwrites dst. */
1708
0
    wc_Sha3Free(dst);
1709
0
    XMEMCPY(dst, src, sizeof(wc_Sha3));
1710
1711
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_SHA3)
1712
    ret = wolfAsync_DevCopy(&src->asyncDev, &dst->asyncDev);
1713
#endif
1714
1715
#if defined(PSOC6_HASH_SHA3)
1716
    /* Re-initialize internal pointers in hash_state that point inside sha_buffers */
1717
    dst->hash_state.hash = (uint8_t*)((cy_stc_crypto_v2_sha3_buffers_t *)&dst->sha_buffers)->hash;
1718
#endif
1719
1720
#ifdef WOLFSSL_HASH_FLAGS
1721
     dst->flags |= WC_HASH_FLAG_ISCOPY;
1722
#endif
1723
1724
0
    return ret;
1725
0
}
1726
1727
#if !(defined(WOLFSSL_NOSHA3_224) && defined(WOLFSSL_NOSHA3_256) && \
1728
      defined(WOLFSSL_NOSHA3_384) && defined(WOLFSSL_NOSHA3_512))
1729
/* Calculate the SHA3-224 hash based on all the message data so far.
1730
 * More message data can be added, after this operation, using the current
1731
 * state.
1732
 *
1733
 * sha3  wc_Sha3 object holding state.
1734
 * hash  Buffer to hold the hash result. Must be at least 28 bytes.
1735
 * p     Number of 64-bit numbers in a block of data to process.
1736
 * len   Number of bytes in output.
1737
 * returns 0 on success.
1738
 */
1739
static int wc_Sha3GetHash(wc_Sha3* sha3, byte* hash, word32 p, word32 len)
1740
0
{
1741
0
    int ret;
1742
0
    WC_DECLARE_VAR(tmpSha3, wc_Sha3, 1, sha3 ? sha3->heap : NULL);
1743
1744
0
    if (sha3 == NULL || hash == NULL)
1745
0
        return BAD_FUNC_ARG;
1746
1747
0
    WC_ALLOC_VAR_EX(tmpSha3, wc_Sha3, 1, sha3->heap, DYNAMIC_TYPE_TMP_BUFFER,
1748
0
                    return MEMORY_E);
1749
1750
0
    XMEMSET(tmpSha3, 0, sizeof(*tmpSha3));
1751
0
    ret = wc_Sha3Copy(sha3, tmpSha3);
1752
0
    if (ret == 0) {
1753
0
        ret = wc_Sha3Final(tmpSha3, hash, p, len);
1754
0
    }
1755
1756
0
    WC_FREE_VAR_EX(tmpSha3, sha3->heap, DYNAMIC_TYPE_TMP_BUFFER);
1757
0
    return ret;
1758
0
}
1759
#endif
1760
1761
#ifndef WOLFSSL_NOSHA3_224
1762
/* Initialize the state for a SHA3-224 hash operation.
1763
 *
1764
 * sha3   wc_Sha3 object holding state.
1765
 * heap   Heap reference for dynamic memory allocation. (Used in async ops.)
1766
 * devId  Device identifier for asynchronous operation.
1767
 * returns 0 on success.
1768
 */
1769
int wc_InitSha3_224(wc_Sha3* sha3, void* heap, int devId)
1770
0
{
1771
0
    return wc_InitSha3(sha3, heap, devId);
1772
0
}
1773
1774
/* Update the SHA3-224 hash state with message data.
1775
 *
1776
 * sha3  wc_Sha3 object holding state.
1777
 * data  Message data to be hashed.
1778
 * len   Length of the message data.
1779
 * returns 0 on success.
1780
 */
1781
int wc_Sha3_224_Update(wc_Sha3* sha3, const byte* data, word32 len)
1782
0
{
1783
0
    return wc_Sha3Update(sha3, data, len, WC_SHA3_224_COUNT);
1784
0
}
1785
1786
/* Calculate the SHA3-224 hash based on all the message data seen.
1787
 * The state is initialized ready for a new message to hash.
1788
 *
1789
 * sha3  wc_Sha3 object holding state.
1790
 * hash  Buffer to hold the hash result. Must be at least 28 bytes.
1791
 * returns 0 on success.
1792
 */
1793
int wc_Sha3_224_Final(wc_Sha3* sha3, byte* hash)
1794
0
{
1795
0
    return wc_Sha3Final(sha3, hash, WC_SHA3_224_COUNT, WC_SHA3_224_DIGEST_SIZE);
1796
0
}
1797
1798
/* Dispose of any dynamically allocated data from the SHA3-224 operation.
1799
 * (Required for async ops.)
1800
 *
1801
 * sha3  wc_Sha3 object holding state.
1802
 * returns 0 on success.
1803
 */
1804
void wc_Sha3_224_Free(wc_Sha3* sha3)
1805
0
{
1806
0
    wc_Sha3Free(sha3);
1807
0
}
1808
1809
0
int wc_Sha3_224_Reset(wc_Sha3* sha3) {
1810
0
    return wc_Sha3Reset(sha3);
1811
0
}
1812
1813
/* Calculate the SHA3-224 hash based on all the message data so far.
1814
 * More message data can be added, after this operation, using the current
1815
 * state.
1816
 *
1817
 * sha3  wc_Sha3 object holding state.
1818
 * hash  Buffer to hold the hash result. Must be at least 28 bytes.
1819
 * returns 0 on success.
1820
 */
1821
int wc_Sha3_224_GetHash(wc_Sha3* sha3, byte* hash)
1822
0
{
1823
0
    return wc_Sha3GetHash(sha3, hash, WC_SHA3_224_COUNT, WC_SHA3_224_DIGEST_SIZE);
1824
0
}
1825
1826
/* Copy the state of the SHA3-224 operation.
1827
 *
1828
 * src  wc_Sha3 object holding state top copy.
1829
 * dst  wc_Sha3 object to copy into.
1830
 * returns 0 on success.
1831
 */
1832
int wc_Sha3_224_Copy(wc_Sha3* src, wc_Sha3* dst)
1833
0
{
1834
0
    return wc_Sha3Copy(src, dst);
1835
0
}
1836
#endif
1837
1838
#ifndef WOLFSSL_NOSHA3_256
1839
/* Initialize the state for a SHA3-256 hash operation.
1840
 *
1841
 * sha3   wc_Sha3 object holding state.
1842
 * heap   Heap reference for dynamic memory allocation. (Used in async ops.)
1843
 * devId  Device identifier for asynchronous operation.
1844
 * returns 0 on success.
1845
 */
1846
int wc_InitSha3_256(wc_Sha3* sha3, void* heap, int devId)
1847
0
{
1848
0
    return wc_InitSha3(sha3, heap, devId);
1849
0
}
1850
1851
/* Update the SHA3-256 hash state with message data.
1852
 *
1853
 * sha3  wc_Sha3 object holding state.
1854
 * data  Message data to be hashed.
1855
 * len   Length of the message data.
1856
 * returns 0 on success.
1857
 */
1858
int wc_Sha3_256_Update(wc_Sha3* sha3, const byte* data, word32 len)
1859
0
{
1860
0
    return wc_Sha3Update(sha3, data, len, WC_SHA3_256_COUNT);
1861
0
}
1862
1863
/* Calculate the SHA3-256 hash based on all the message data seen.
1864
 * The state is initialized ready for a new message to hash.
1865
 *
1866
 * sha3  wc_Sha3 object holding state.
1867
 * hash  Buffer to hold the hash result. Must be at least 32 bytes.
1868
 * returns 0 on success.
1869
 */
1870
int wc_Sha3_256_Final(wc_Sha3* sha3, byte* hash)
1871
0
{
1872
0
    return wc_Sha3Final(sha3, hash, WC_SHA3_256_COUNT, WC_SHA3_256_DIGEST_SIZE);
1873
0
}
1874
1875
/* Dispose of any dynamically allocated data from the SHA3-256 operation.
1876
 * (Required for async ops.)
1877
 *
1878
 * sha3  wc_Sha3 object holding state.
1879
 * returns 0 on success.
1880
 */
1881
void wc_Sha3_256_Free(wc_Sha3* sha3)
1882
0
{
1883
0
    wc_Sha3Free(sha3);
1884
0
}
1885
1886
0
int wc_Sha3_256_Reset(wc_Sha3* sha3) {
1887
0
    return wc_Sha3Reset(sha3);
1888
0
}
1889
1890
/* Calculate the SHA3-256 hash based on all the message data so far.
1891
 * More message data can be added, after this operation, using the current
1892
 * state.
1893
 *
1894
 * sha3  wc_Sha3 object holding state.
1895
 * hash  Buffer to hold the hash result. Must be at least 32 bytes.
1896
 * returns 0 on success.
1897
 */
1898
int wc_Sha3_256_GetHash(wc_Sha3* sha3, byte* hash)
1899
0
{
1900
0
    return wc_Sha3GetHash(sha3, hash, WC_SHA3_256_COUNT, WC_SHA3_256_DIGEST_SIZE);
1901
0
}
1902
1903
/* Copy the state of the SHA3-256 operation.
1904
 *
1905
 * src  wc_Sha3 object holding state top copy.
1906
 * dst  wc_Sha3 object to copy into.
1907
 * returns 0 on success.
1908
 */
1909
int wc_Sha3_256_Copy(wc_Sha3* src, wc_Sha3* dst)
1910
0
{
1911
0
    return wc_Sha3Copy(src, dst);
1912
0
}
1913
#endif
1914
1915
#ifndef WOLFSSL_NOSHA3_384
1916
/* Initialize the state for a SHA3-384 hash operation.
1917
 *
1918
 * sha3   wc_Sha3 object holding state.
1919
 * heap   Heap reference for dynamic memory allocation. (Used in async ops.)
1920
 * devId  Device identifier for asynchronous operation.
1921
 * returns 0 on success.
1922
 */
1923
int wc_InitSha3_384(wc_Sha3* sha3, void* heap, int devId)
1924
0
{
1925
0
    return wc_InitSha3(sha3, heap, devId);
1926
0
}
1927
1928
/* Update the SHA3-384 hash state with message data.
1929
 *
1930
 * sha3  wc_Sha3 object holding state.
1931
 * data  Message data to be hashed.
1932
 * len   Length of the message data.
1933
 * returns 0 on success.
1934
 */
1935
int wc_Sha3_384_Update(wc_Sha3* sha3, const byte* data, word32 len)
1936
0
{
1937
0
    return wc_Sha3Update(sha3, data, len, WC_SHA3_384_COUNT);
1938
0
}
1939
1940
/* Calculate the SHA3-384 hash based on all the message data seen.
1941
 * The state is initialized ready for a new message to hash.
1942
 *
1943
 * sha3  wc_Sha3 object holding state.
1944
 * hash  Buffer to hold the hash result. Must be at least 48 bytes.
1945
 * returns 0 on success.
1946
 */
1947
int wc_Sha3_384_Final(wc_Sha3* sha3, byte* hash)
1948
0
{
1949
0
    return wc_Sha3Final(sha3, hash, WC_SHA3_384_COUNT, WC_SHA3_384_DIGEST_SIZE);
1950
0
}
1951
1952
/* Dispose of any dynamically allocated data from the SHA3-384 operation.
1953
 * (Required for async ops.)
1954
 *
1955
 * sha3  wc_Sha3 object holding state.
1956
 * returns 0 on success.
1957
 */
1958
void wc_Sha3_384_Free(wc_Sha3* sha3)
1959
0
{
1960
0
    wc_Sha3Free(sha3);
1961
0
}
1962
1963
0
int wc_Sha3_384_Reset(wc_Sha3* sha3) {
1964
0
    return wc_Sha3Reset(sha3);
1965
0
}
1966
1967
/* Calculate the SHA3-384 hash based on all the message data so far.
1968
 * More message data can be added, after this operation, using the current
1969
 * state.
1970
 *
1971
 * sha3  wc_Sha3 object holding state.
1972
 * hash  Buffer to hold the hash result. Must be at least 48 bytes.
1973
 * returns 0 on success.
1974
 */
1975
int wc_Sha3_384_GetHash(wc_Sha3* sha3, byte* hash)
1976
0
{
1977
0
    return wc_Sha3GetHash(sha3, hash, WC_SHA3_384_COUNT, WC_SHA3_384_DIGEST_SIZE);
1978
0
}
1979
1980
/* Copy the state of the SHA3-384 operation.
1981
 *
1982
 * src  wc_Sha3 object holding state top copy.
1983
 * dst  wc_Sha3 object to copy into.
1984
 * returns 0 on success.
1985
 */
1986
int wc_Sha3_384_Copy(wc_Sha3* src, wc_Sha3* dst)
1987
0
{
1988
0
    return wc_Sha3Copy(src, dst);
1989
0
}
1990
#endif
1991
1992
#ifndef WOLFSSL_NOSHA3_512
1993
/* Initialize the state for a SHA3-512 hash operation.
1994
 *
1995
 * sha3   wc_Sha3 object holding state.
1996
 * heap   Heap reference for dynamic memory allocation. (Used in async ops.)
1997
 * devId  Device identifier for asynchronous operation.
1998
 * returns 0 on success.
1999
 */
2000
int wc_InitSha3_512(wc_Sha3* sha3, void* heap, int devId)
2001
0
{
2002
0
    return wc_InitSha3(sha3, heap, devId);
2003
0
}
2004
2005
/* Update the SHA3-512 hash state with message data.
2006
 *
2007
 * sha3  wc_Sha3 object holding state.
2008
 * data  Message data to be hashed.
2009
 * len   Length of the message data.
2010
 * returns 0 on success.
2011
 */
2012
int wc_Sha3_512_Update(wc_Sha3* sha3, const byte* data, word32 len)
2013
0
{
2014
0
    return wc_Sha3Update(sha3, data, len, WC_SHA3_512_COUNT);
2015
0
}
2016
2017
/* Calculate the SHA3-512 hash based on all the message data seen.
2018
 * The state is initialized ready for a new message to hash.
2019
 *
2020
 * sha3  wc_Sha3 object holding state.
2021
 * hash  Buffer to hold the hash result. Must be at least 64 bytes.
2022
 * returns 0 on success.
2023
 */
2024
int wc_Sha3_512_Final(wc_Sha3* sha3, byte* hash)
2025
0
{
2026
0
    return wc_Sha3Final(sha3, hash, WC_SHA3_512_COUNT, WC_SHA3_512_DIGEST_SIZE);
2027
0
}
2028
2029
/* Dispose of any dynamically allocated data from the SHA3-512 operation.
2030
 * (Required for async ops.)
2031
 *
2032
 * sha3  wc_Sha3 object holding state.
2033
 * returns 0 on success.
2034
 */
2035
void wc_Sha3_512_Free(wc_Sha3* sha3)
2036
0
{
2037
0
    wc_Sha3Free(sha3);
2038
0
}
2039
2040
0
int wc_Sha3_512_Reset(wc_Sha3* sha3) {
2041
0
    return wc_Sha3Reset(sha3);
2042
0
}
2043
2044
/* Calculate the SHA3-512 hash based on all the message data so far.
2045
 * More message data can be added, after this operation, using the current
2046
 * state.
2047
 *
2048
 * sha3  wc_Sha3 object holding state.
2049
 * hash  Buffer to hold the hash result. Must be at least 64 bytes.
2050
 * returns 0 on success.
2051
 */
2052
int wc_Sha3_512_GetHash(wc_Sha3* sha3, byte* hash)
2053
0
{
2054
0
    return wc_Sha3GetHash(sha3, hash, WC_SHA3_512_COUNT, WC_SHA3_512_DIGEST_SIZE);
2055
0
}
2056
2057
/* Copy the state of the SHA3-512 operation.
2058
 *
2059
 * src  wc_Sha3 object holding state top copy.
2060
 * dst  wc_Sha3 object to copy into.
2061
 * returns 0 on success.
2062
 */
2063
int wc_Sha3_512_Copy(wc_Sha3* src, wc_Sha3* dst)
2064
0
{
2065
0
    return wc_Sha3Copy(src, dst);
2066
0
}
2067
#endif
2068
2069
#ifdef WOLFSSL_HASH_FLAGS
2070
int wc_Sha3_SetFlags(wc_Sha3* sha3, word32 flags)
2071
{
2072
    if (sha3) {
2073
        sha3->flags = flags;
2074
    }
2075
    return 0;
2076
}
2077
int wc_Sha3_GetFlags(wc_Sha3* sha3, word32* flags)
2078
{
2079
    if (sha3 && flags) {
2080
        *flags = sha3->flags;
2081
    }
2082
    return 0;
2083
}
2084
#endif
2085
2086
#ifdef WOLFSSL_SHAKE128
2087
/* Initialize the state for a Shake128 hash operation.
2088
 *
2089
 * shake  wc_Shake object holding state.
2090
 * heap   Heap reference for dynamic memory allocation. (Used in async ops.)
2091
 * devId  Device identifier for asynchronous operation.
2092
 * returns 0 on success.
2093
 */
2094
int wc_InitShake128(wc_Shake* shake, void* heap, int devId)
2095
0
{
2096
0
    int ret = wc_InitSha3(shake, heap, devId);
2097
/* The PSoC6 wc_Sha3 variant has no hashType member */
2098
#if defined(WOLF_CRYPTO_CB) && !defined(PSOC6_HASH_SHA3)
2099
    /* SHAKE never hits the SHA3 auto-detect, so set the type here for the
2100
     * Copy/Free callback dispatch. */
2101
    if (ret == 0)
2102
        shake->hashType = WC_HASH_TYPE_SHAKE128;
2103
#endif
2104
0
    return ret;
2105
0
}
2106
2107
#if defined(PSOC6_HASH_SHA3)
2108
2109
int wc_Shake128_Update(wc_Shake* shake, const byte* data, word32 len)
2110
{
2111
    int ret;
2112
    if (shake == NULL || (data == NULL && len > 0)) {
2113
         return BAD_FUNC_ARG;
2114
    }
2115
2116
    if (data == NULL) {
2117
        /* len is 0 here: valid, but do nothing */
2118
        return 0;
2119
    }
2120
2121
    /* Lock the mutex to perform crypto operations */
2122
    ret = wolfSSL_CryptHwMutexLock();
2123
    if (ret == 0) {
2124
        /* Perform SHA3 on the input data and update the hash state */
2125
        ret = wc_Psoc6_Sha3_Update(shake, data, len, WC_SHA3_128_COUNT);
2126
        /* Release the lock */
2127
        wolfSSL_CryptHwMutexUnLock();
2128
    }
2129
2130
    return ret;
2131
}
2132
2133
int wc_Shake128_Final(wc_Shake* shake, byte* hash, word32 hashLen)
2134
{
2135
    int ret;
2136
2137
    if (shake == NULL || hash == NULL) {
2138
        return BAD_FUNC_ARG;
2139
    }
2140
2141
    /* Lock the mutex to perform crypto operations */
2142
    ret = wolfSSL_CryptHwMutexLock();
2143
    if (ret == 0) {
2144
        /* Finalize SHA3 operations and produce digest */
2145
        ret = wc_Psoc6_Sha3_Final(shake, 0x1f, hash, WC_SHA3_128_COUNT, hashLen);
2146
        if (ret == 0) {
2147
            /* Initialize hash state for SHA-3 operation */
2148
            ret = wc_Psoc6_Sha3_Init(shake);
2149
        }
2150
        /* Release the lock */
2151
        wolfSSL_CryptHwMutexUnLock();
2152
    }
2153
2154
    return ret;
2155
2156
}
2157
2158
int wc_Shake128_Absorb(wc_Shake* shake, const byte* data, word32 len)
2159
{
2160
    int ret;
2161
2162
    if ((shake == NULL) || (data == NULL && len != 0)) {
2163
        return BAD_FUNC_ARG;
2164
    }
2165
2166
    /* Lock the mutex to perform crypto operations */
2167
    ret = wolfSSL_CryptHwMutexLock();
2168
    if (ret == 0) {
2169
        /* Perform SHA3 on the input data and update the hash state */
2170
        ret = wc_Psoc6_Sha3_Update(shake, data, len, WC_SHA3_128_COUNT);
2171
        if (ret == 0) {
2172
            /* Finalize SHA3 operations and produce digest */
2173
            ret = wc_Psoc6_Sha3_Final(shake, 0x1f, NULL, WC_SHA3_128_COUNT, 0);
2174
        }
2175
        /* Release the lock */
2176
        wolfSSL_CryptHwMutexUnLock();
2177
    }
2178
2179
    return ret;
2180
}
2181
2182
2183
int wc_Shake128_SqueezeBlocks(wc_Shake* shake, byte* out, word32 blockCnt)
2184
{
2185
    int ret;
2186
    if ((shake == NULL) || (out == NULL && blockCnt != 0)) {
2187
        return BAD_FUNC_ARG;
2188
    }
2189
2190
    /* Lock the mutex to perform crypto operations */
2191
    ret = wolfSSL_CryptHwMutexLock();
2192
    if (ret == 0) {
2193
        /* Squeeze output blocks from current hash state */
2194
        ret = wc_Psoc6_Shake_SqueezeBlocks(shake, out, blockCnt);
2195
        /* Release the lock */
2196
        wolfSSL_CryptHwMutexUnLock();
2197
    }
2198
2199
    return ret;
2200
}
2201
#else
2202
/* Update the SHAKE128 hash state with message data.
2203
 *
2204
 * shake  wc_Shake object holding state.
2205
 * data  Message data to be hashed.
2206
 * len   Length of the message data.
2207
 * returns 0 on success.
2208
 */
2209
int wc_Shake128_Update(wc_Shake* shake, const byte* data, word32 len)
2210
0
{
2211
0
    if (shake == NULL) {
2212
0
        return BAD_FUNC_ARG;
2213
0
    }
2214
2215
0
    if (data == NULL && len == 0) {
2216
        /* valid, but do nothing */
2217
0
        return 0;
2218
0
    }
2219
2220
0
    if (data == NULL) {
2221
0
        return BAD_FUNC_ARG;
2222
0
    }
2223
2224
#ifdef WOLF_CRYPTO_CB
2225
    #ifndef WOLF_CRYPTO_CB_FIND
2226
    if (shake->devId != INVALID_DEVID)
2227
    #endif
2228
    {
2229
        int ret = wc_CryptoCb_Shake(shake, WC_HASH_TYPE_SHAKE128, data, len,
2230
            NULL, 0);
2231
        if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE))
2232
            return ret;
2233
        /* fall-through when unavailable */
2234
    }
2235
#endif
2236
2237
0
    return Sha3Update(shake, data, len, WC_SHA3_128_COUNT);
2238
0
}
2239
2240
/* Calculate the SHAKE128 hash based on all the message data seen.
2241
 * The state is initialized ready for a new message to hash.
2242
 *
2243
 * shake  wc_Shake object holding state.
2244
 * hash  Buffer to hold the hash result. Must be at least 64 bytes.
2245
 * returns 0 on success.
2246
 */
2247
int wc_Shake128_Final(wc_Shake* shake, byte* hash, word32 hashLen)
2248
0
{
2249
0
    int ret;
2250
2251
0
    if (shake == NULL || hash == NULL) {
2252
0
        return BAD_FUNC_ARG;
2253
0
    }
2254
2255
#ifdef WOLF_CRYPTO_CB
2256
    #ifndef WOLF_CRYPTO_CB_FIND
2257
    if (shake->devId != INVALID_DEVID)
2258
    #endif
2259
    {
2260
        ret = wc_CryptoCb_Shake(shake, WC_HASH_TYPE_SHAKE128, NULL, 0, hash,
2261
            hashLen);
2262
        if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE))
2263
            return ret;
2264
        /* fall-through when unavailable */
2265
    }
2266
#endif
2267
2268
0
    ret = Sha3Final(shake, 0x1f, hash, WC_SHA3_128_COUNT, hashLen);
2269
0
    if (ret != 0)
2270
0
        return ret;
2271
2272
0
    ret = InitSha3(shake);  /* reset state */
2273
#ifdef WOLF_CRYPTO_CB
2274
    /* Restore the type cleared by the reset for Copy/Free dispatch. */
2275
    if (ret == 0)
2276
        shake->hashType = WC_HASH_TYPE_SHAKE128;
2277
#endif
2278
0
    return ret;
2279
0
}
2280
2281
/* Absorb the data for squeezing.
2282
 *
2283
 * Update and final with data but no output and no reset
2284
 *
2285
 * shake  wc_Shake object holding state.
2286
 * data  Data to absorb.
2287
 * len  Length of d to absorb in bytes.
2288
 * returns 0 on success.
2289
 */
2290
int wc_Shake128_Absorb(wc_Shake* shake, const byte* data, word32 len)
2291
0
{
2292
0
    int ret;
2293
2294
0
    if ((shake == NULL) || (data == NULL && len != 0)) {
2295
0
        return BAD_FUNC_ARG;
2296
0
    }
2297
2298
0
    ret = Sha3Update(shake, data, len, WC_SHA3_128_COUNT);
2299
0
    if (ret == 0) {
2300
0
        byte hash[1];
2301
0
        ret = Sha3Final(shake, 0x1f, hash, WC_SHA3_128_COUNT, 0);
2302
0
    }
2303
    /* No partial data. */
2304
0
    shake->i = 0;
2305
2306
0
    return ret;
2307
0
}
2308
2309
#ifdef WC_C_DYNAMIC_FALLBACK
2310
    #undef SHA3_BLOCK
2311
    #undef SHA3_BLOCK_N
2312
    #define SHA3_BLOCK (shake->sha3_block)
2313
    #define SHA3_BLOCK_N (shake->sha3_block_n)
2314
#endif
2315
2316
/* Squeeze the state to produce pseudo-random output.
2317
 *
2318
 * shake  wc_Shake object holding state.
2319
 * out  Output buffer.
2320
 * blockCnt  Number of blocks to write.
2321
 * returns 0 on success.
2322
 */
2323
int wc_Shake128_SqueezeBlocks(wc_Shake* shake, byte* out, word32 blockCnt)
2324
0
{
2325
#if defined(WC_C_DYNAMIC_FALLBACK) && defined(USE_INTEL_SPEEDUP)
2326
    void (*sha3_block)(word64 *s);
2327
#endif
2328
2329
0
    if ((shake == NULL) || (out == NULL && blockCnt != 0)) {
2330
0
        return BAD_FUNC_ARG;
2331
0
    }
2332
2333
#ifdef USE_INTEL_SPEEDUP
2334
#ifdef WC_C_DYNAMIC_FALLBACK
2335
    sha3_block = SHA3_BLOCK;
2336
#endif
2337
2338
    if (SHA3_BLOCK_VREGS(sha3_block)) {
2339
        int ret = SAVE_VECTOR_REGISTERS2();
2340
        if (ret != 0) {
2341
#ifdef WC_C_DYNAMIC_FALLBACK
2342
            sha3_block = BlockSha3;
2343
#else
2344
            return ret;
2345
#endif
2346
        }
2347
    }
2348
#endif /* USE_INTEL_SPEEDUP */
2349
2350
0
    for (; (blockCnt > 0); blockCnt--) {
2351
    #ifdef SHA3_FUNC_PTR
2352
        (*sha3_block)(shake->s);
2353
    #else
2354
0
        BlockSha3(shake->s);
2355
0
    #endif
2356
    #if defined(BIG_ENDIAN_ORDER)
2357
        ByteReverseWords64((word64*)out, shake->s, WC_SHA3_128_COUNT * 8);
2358
    #elif defined(WOLFSSL_WIDE_BYTE)
2359
        Sha3SqueezeBytes(out, shake->s, WC_SHA3_128_COUNT * 8);
2360
    #else
2361
0
        XMEMCPY(out, shake->s, WC_SHA3_128_COUNT * 8);
2362
0
    #endif
2363
0
        out += WC_SHA3_128_COUNT * 8;
2364
0
    }
2365
2366
#ifdef USE_INTEL_SPEEDUP
2367
    if (SHA3_BLOCK_VREGS(sha3_block))
2368
        RESTORE_VECTOR_REGISTERS();
2369
#endif
2370
2371
0
    return 0;
2372
0
}
2373
#endif
2374
2375
2376
/* Dispose of any dynamically allocated data from the SHAKE128 operation.
2377
 * (Required for async ops.)
2378
 *
2379
 * shake  wc_Shake object holding state.
2380
 * returns 0 on success.
2381
 */
2382
void wc_Shake128_Free(wc_Shake* shake)
2383
0
{
2384
0
    wc_Sha3Free(shake);
2385
0
}
2386
2387
0
int wc_Shake128_Reset(wc_Shake* shake) {
2388
0
    int ret = wc_Sha3Reset(shake);
2389
#if defined(WOLF_CRYPTO_CB) && !defined(PSOC6_HASH_SHA3)
2390
    /* SHAKE never hits the SHA3 auto-detect, so restore the type here for
2391
     * the Copy/Free callback dispatch. */
2392
    if (ret == 0)
2393
        shake->hashType = WC_HASH_TYPE_SHAKE128;
2394
#endif
2395
0
    return ret;
2396
0
}
2397
2398
/* Copy the state of the SHA3-512 operation.
2399
 *
2400
 * src  wc_Shake object holding state top copy.
2401
 * dst  wc_Shake object to copy into.
2402
 * returns 0 on success.
2403
 */
2404
int wc_Shake128_Copy(wc_Shake* src, wc_Shake* dst)
2405
0
{
2406
0
    return wc_Sha3Copy(src, dst);
2407
0
}
2408
#endif
2409
2410
#ifdef WOLFSSL_SHAKE256
2411
/* Initialize the state for a Shake256 hash operation.
2412
 *
2413
 * shake  wc_Shake object holding state.
2414
 * heap   Heap reference for dynamic memory allocation. (Used in async ops.)
2415
 * devId  Device identifier for asynchronous operation.
2416
 * returns 0 on success.
2417
 */
2418
int wc_InitShake256(wc_Shake* shake, void* heap, int devId)
2419
0
{
2420
0
    int ret = wc_InitSha3(shake, heap, devId);
2421
/* The PSoC6 wc_Sha3 variant has no hashType member */
2422
#if defined(WOLF_CRYPTO_CB) && !defined(PSOC6_HASH_SHA3)
2423
    /* SHAKE never hits the SHA3 auto-detect, so set the type here for the
2424
     * Copy/Free callback dispatch. */
2425
    if (ret == 0)
2426
        shake->hashType = WC_HASH_TYPE_SHAKE256;
2427
#endif
2428
0
    return ret;
2429
0
}
2430
2431
2432
#ifdef PSOC6_HASH_SHA3
2433
2434
int wc_Shake256_Update(wc_Shake* shake, const byte* data, word32 len)
2435
{
2436
    int ret;
2437
    if (shake == NULL || (data == NULL && len > 0)) {
2438
         return BAD_FUNC_ARG;
2439
    }
2440
2441
    if (data == NULL) {
2442
        /* len is 0 here: valid, but do nothing */
2443
        return 0;
2444
    }
2445
2446
    /* Lock the mutex to perform crypto operations */
2447
    ret = wolfSSL_CryptHwMutexLock();
2448
    if (ret == 0) {
2449
        /* Perform SHA3 on the input data and update the hash state */
2450
        ret = wc_Psoc6_Sha3_Update(shake, data, len, WC_SHA3_256_COUNT);
2451
        /* Release the lock */
2452
        wolfSSL_CryptHwMutexUnLock();
2453
    }
2454
2455
    return ret;
2456
}
2457
2458
int wc_Shake256_Final(wc_Shake* shake, byte* hash, word32 hashLen)
2459
{
2460
    int ret;
2461
    if (shake == NULL || hash == NULL) {
2462
        return BAD_FUNC_ARG;
2463
    }
2464
2465
    /* Lock the mutex to perform crypto operations */
2466
    ret = wolfSSL_CryptHwMutexLock();
2467
    if (ret == 0) {
2468
        /* Finalize SHA3 operations and produce digest */
2469
        ret = wc_Psoc6_Sha3_Final(shake, 0x1f, hash, WC_SHA3_256_COUNT, hashLen);
2470
        if (ret == 0) {
2471
            /* Initialize hash state for SHA-3 operation */
2472
            ret = wc_Psoc6_Sha3_Init(shake);
2473
        }
2474
        /* Release the lock */
2475
        wolfSSL_CryptHwMutexUnLock();
2476
    }
2477
2478
    return ret;
2479
}
2480
2481
int wc_Shake256_Absorb(wc_Shake* shake, const byte* data, word32 len)
2482
{
2483
    int ret;
2484
2485
    if ((shake == NULL) || (data == NULL && len != 0)) {
2486
        return BAD_FUNC_ARG;
2487
    }
2488
2489
    /* Lock the mutex to perform crypto operations */
2490
    ret = wolfSSL_CryptHwMutexLock();
2491
    if (ret == 0) {
2492
        /* Perform SHA3 on the input data and update the hash state */
2493
        ret = wc_Psoc6_Sha3_Update(shake, data, len, WC_SHA3_256_COUNT);
2494
        if (ret == 0) {
2495
            /* Finalize SHA3 operations and produce digest */
2496
            ret = wc_Psoc6_Sha3_Final(shake, 0x1f, NULL, WC_SHA3_256_COUNT, 0);
2497
        }
2498
        /* Release the lock */
2499
        wolfSSL_CryptHwMutexUnLock();
2500
    }
2501
2502
    return ret;
2503
}
2504
2505
int wc_Shake256_SqueezeBlocks(wc_Shake* shake, byte* out, word32 blockCnt)
2506
{
2507
    int ret;
2508
    if ((shake == NULL) || (out == NULL && blockCnt != 0)) {
2509
        return BAD_FUNC_ARG;
2510
    }
2511
2512
    /* Lock the mutex to perform crypto operations */
2513
    ret = wolfSSL_CryptHwMutexLock();
2514
    if (ret == 0) {
2515
        /* Squeeze output blocks from current hash state */
2516
        ret = wc_Psoc6_Shake_SqueezeBlocks(shake, out, blockCnt);
2517
        /* Release the lock */
2518
        wolfSSL_CryptHwMutexUnLock();
2519
    }
2520
2521
    return ret;
2522
}
2523
2524
#else
2525
/* Update the SHAKE256 hash state with message data.
2526
 *
2527
 * shake  wc_Shake object holding state.
2528
 * data  Message data to be hashed.
2529
 * len   Length of the message data.
2530
 * returns 0 on success.
2531
 */
2532
int wc_Shake256_Update(wc_Shake* shake, const byte* data, word32 len)
2533
0
{
2534
0
    if (shake == NULL) {
2535
0
        return BAD_FUNC_ARG;
2536
0
    }
2537
2538
0
    if (data == NULL && len == 0) {
2539
        /* valid, but do nothing */
2540
0
        return 0;
2541
0
    }
2542
2543
0
    if (data == NULL) {
2544
0
        return BAD_FUNC_ARG;
2545
0
    }
2546
2547
#ifdef WOLF_CRYPTO_CB
2548
    #ifndef WOLF_CRYPTO_CB_FIND
2549
    if (shake->devId != INVALID_DEVID)
2550
    #endif
2551
    {
2552
        int ret = wc_CryptoCb_Shake(shake, WC_HASH_TYPE_SHAKE256, data, len,
2553
            NULL, 0);
2554
        if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE))
2555
            return ret;
2556
        /* fall-through when unavailable */
2557
    }
2558
#endif
2559
2560
0
    return Sha3Update(shake, data, len, WC_SHA3_256_COUNT);
2561
0
}
2562
2563
/* Calculate the SHAKE256 hash based on all the message data seen.
2564
 * The state is initialized ready for a new message to hash.
2565
 *
2566
 * shake  wc_Shake object holding state.
2567
 * hash  Buffer to hold the hash result. Must be at least 64 bytes.
2568
 * hashLen Size of hash in bytes.
2569
 * returns 0 on success.
2570
 */
2571
int wc_Shake256_Final(wc_Shake* shake, byte* hash, word32 hashLen)
2572
0
{
2573
0
    int ret;
2574
2575
0
    if (shake == NULL || hash == NULL) {
2576
0
        return BAD_FUNC_ARG;
2577
0
    }
2578
2579
#ifdef WOLF_CRYPTO_CB
2580
    #ifndef WOLF_CRYPTO_CB_FIND
2581
    if (shake->devId != INVALID_DEVID)
2582
    #endif
2583
    {
2584
        ret = wc_CryptoCb_Shake(shake, WC_HASH_TYPE_SHAKE256, NULL, 0, hash,
2585
            hashLen);
2586
        if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE))
2587
            return ret;
2588
        /* fall-through when unavailable */
2589
    }
2590
#endif
2591
2592
0
    ret = Sha3Final(shake, 0x1f, hash, WC_SHA3_256_COUNT, hashLen);
2593
0
    if (ret != 0)
2594
0
        return ret;
2595
2596
0
    ret = InitSha3(shake);  /* reset state */
2597
#ifdef WOLF_CRYPTO_CB
2598
    /* Restore the type cleared by the reset for Copy/Free dispatch. */
2599
    if (ret == 0)
2600
        shake->hashType = WC_HASH_TYPE_SHAKE256;
2601
#endif
2602
0
    return ret;
2603
0
}
2604
2605
/* Absorb the data for squeezing.
2606
 *
2607
 * Update and final with data but no output and no reset
2608
 *
2609
 * shake  wc_Shake object holding state.
2610
 * data  Data to absorb.
2611
 * len  Length of d to absorb in bytes.
2612
 * returns 0 on success.
2613
 */
2614
int wc_Shake256_Absorb(wc_Shake* shake, const byte* data, word32 len)
2615
0
{
2616
0
    int ret;
2617
2618
0
    if ((shake == NULL) || (data == NULL && len != 0)) {
2619
0
        return BAD_FUNC_ARG;
2620
0
    }
2621
2622
0
    ret = Sha3Update(shake, data, len, WC_SHA3_256_COUNT);
2623
0
    if (ret == 0) {
2624
0
        byte hash[1];
2625
0
        ret = Sha3Final(shake, 0x1f, hash, WC_SHA3_256_COUNT, 0);
2626
0
    }
2627
    /* No partial data. */
2628
0
    shake->i = 0;
2629
2630
0
    return ret;
2631
0
}
2632
2633
/* Squeeze the state to produce pseudo-random output.
2634
 *
2635
 * shake  wc_Shake object holding state.
2636
 * out  Output buffer.
2637
 * blockCnt  Number of blocks to write.
2638
 * returns 0 on success.
2639
 */
2640
int wc_Shake256_SqueezeBlocks(wc_Shake* shake, byte* out, word32 blockCnt)
2641
0
{
2642
#if defined(WC_C_DYNAMIC_FALLBACK) && defined(USE_INTEL_SPEEDUP)
2643
    void (*sha3_block)(word64 *s);
2644
#endif
2645
2646
0
    if ((shake == NULL) || (out == NULL && blockCnt != 0)) {
2647
0
        return BAD_FUNC_ARG;
2648
0
    }
2649
2650
#ifdef USE_INTEL_SPEEDUP
2651
#ifdef WC_C_DYNAMIC_FALLBACK
2652
    sha3_block = SHA3_BLOCK;
2653
#endif
2654
2655
    if (SHA3_BLOCK_VREGS(sha3_block)) {
2656
        int ret = SAVE_VECTOR_REGISTERS2();
2657
        if (ret != 0) {
2658
#ifdef WC_C_DYNAMIC_FALLBACK
2659
            sha3_block = BlockSha3;
2660
#else
2661
            return ret;
2662
#endif
2663
        }
2664
    }
2665
#endif /* USE_INTEL_SPEEDUP */
2666
2667
0
    for (; (blockCnt > 0); blockCnt--) {
2668
    #ifdef SHA3_FUNC_PTR
2669
        (*sha3_block)(shake->s);
2670
    #else
2671
0
        BlockSha3(shake->s);
2672
0
    #endif
2673
    #if defined(BIG_ENDIAN_ORDER)
2674
        ByteReverseWords64((word64*)out, shake->s, WC_SHA3_256_COUNT * 8);
2675
    #elif defined(WOLFSSL_WIDE_BYTE)
2676
        Sha3SqueezeBytes(out, shake->s, WC_SHA3_256_COUNT * 8);
2677
    #else
2678
0
        XMEMCPY(out, shake->s, WC_SHA3_256_COUNT * 8);
2679
0
    #endif
2680
0
        out += WC_SHA3_256_COUNT * 8;
2681
0
    }
2682
2683
#ifdef USE_INTEL_SPEEDUP
2684
    if (SHA3_BLOCK_VREGS(sha3_block))
2685
        RESTORE_VECTOR_REGISTERS();
2686
#endif
2687
2688
0
    return 0;
2689
0
}
2690
#endif
2691
2692
/* Dispose of any dynamically allocated data from the SHAKE256 operation.
2693
 * (Required for async ops.)
2694
 *
2695
 * shake  wc_Shake object holding state.
2696
 * returns 0 on success.
2697
 */
2698
void wc_Shake256_Free(wc_Shake* shake)
2699
0
{
2700
0
    wc_Sha3Free(shake);
2701
0
}
2702
2703
0
int wc_Shake256_Reset(wc_Shake* shake) {
2704
0
    int ret = wc_Sha3Reset(shake);
2705
#if defined(WOLF_CRYPTO_CB) && !defined(PSOC6_HASH_SHA3)
2706
    /* SHAKE never hits the SHA3 auto-detect, so restore the type here for
2707
     * the Copy/Free callback dispatch. */
2708
    if (ret == 0)
2709
        shake->hashType = WC_HASH_TYPE_SHAKE256;
2710
#endif
2711
0
    return ret;
2712
0
}
2713
2714
/* Copy the state of the SHA3-512 operation.
2715
 *
2716
 * src  wc_Shake object holding state top copy.
2717
 * dst  wc_Shake object to copy into.
2718
 * returns 0 on success.
2719
 */
2720
int wc_Shake256_Copy(wc_Shake* src, wc_Shake* dst)
2721
0
{
2722
0
    return wc_Sha3Copy(src, dst);
2723
0
}
2724
#endif
2725
2726
#if (defined(WOLFSSL_KMAC) || defined(WOLFSSL_CSHAKE)) && \
2727
    defined(WC_SHA3_SW_KECCAK)
2728
/* cSHAKE and KMAC - NIST SP 800-185.
2729
 *
2730
 * cSHAKE is a customizable SHAKE; KMAC is cSHAKE keyed with the function name
2731
 * "KMAC". Both feed length-prefixed strings into the SHAKE (KECCAK) sponge and
2732
 * (when customized) finalize with the cSHAKE domain-separation pad byte 0x04
2733
 * rather than SHAKE's 0x1f. The heavy lifting - absorbing message bytes and
2734
 * squeezing output - reuses the software Sha3Update()/Sha3Final() helpers
2735
 * above. The KMAC-specific code is compiled only when WOLFSSL_KMAC is set;
2736
 * cSHAKE is also available on its own via WOLFSSL_CSHAKE. */
2737
2738
/* left_encode(value) per NIST SP 800-185, section 2.3.1.
2739
 *
2740
 * A length byte giving the number of value bytes, followed by that many bytes
2741
 * of the value in big-endian (most significant first) order.
2742
 *
2743
 * @param [out] out    Buffer to write encoding to. Must hold at least 9 bytes.
2744
 * @param [in]  value  Value to encode. 0 encodes as the bytes 0x01 0x00.
2745
 *
2746
 * @return  Number of bytes written to out - between 2 and 9.
2747
 */
2748
static word32 KmacLeftEncode(byte* out, word64 value)
2749
{
2750
    word32 n = 1;
2751
    word64 v = value;
2752
2753
    /* Build up the number of significant bytes (min 1) by halving: test the
2754
     * top 32 bits, then each smaller half, shifting away counted bytes. */
2755
    if ((v >> 32) != 0) { n += 4; v >>= 32; }
2756
    if ((v >> 16) != 0) { n += 2; v >>= 16; }
2757
    if ((v >>  8) != 0) { n += 1;           }
2758
2759
    /* Length byte then the n value bytes big-endian.  Enter the switch at
2760
     * case n and fall through, storing least-significant byte first into
2761
     * out[n]..out[1]. */
2762
    out[0] = (byte)n;
2763
    switch (n) {
2764
        case 8: out[8] = (byte)value; value >>= 8; FALL_THROUGH;
2765
        case 7: out[7] = (byte)value; value >>= 8; FALL_THROUGH;
2766
        case 6: out[6] = (byte)value; value >>= 8; FALL_THROUGH;
2767
        case 5: out[5] = (byte)value; value >>= 8; FALL_THROUGH;
2768
        case 4: out[4] = (byte)value; value >>= 8; FALL_THROUGH;
2769
        case 3: out[3] = (byte)value; value >>= 8; FALL_THROUGH;
2770
        case 2: out[2] = (byte)value; value >>= 8; FALL_THROUGH;
2771
        default: out[1] = (byte)value;
2772
    }
2773
2774
    return n + 1;
2775
}
2776
2777
#ifdef WOLFSSL_KMAC
2778
/* right_encode(value) per NIST SP 800-185, section 2.3.1. Only used by KMAC
2779
 * (cSHAKE does not bind an output length).
2780
 *
2781
 * The value in big-endian (most significant first) order, followed by a length
2782
 * byte giving the number of value bytes.
2783
 *
2784
 * @param [out] out    Buffer to write encoding to. Must hold at least 9 bytes.
2785
 * @param [in]  value  Value to encode. 0 encodes as the bytes 0x00 0x01.
2786
 *
2787
 * @return  Number of bytes written to out - between 2 and 9.
2788
 */
2789
static word32 KmacRightEncode(byte* out, word64 value)
2790
{
2791
    word32 n = 1;
2792
    word64 v = value;
2793
2794
    /* Build up the number of significant bytes (min 1) by halving: test the
2795
     * top 32 bits, then each smaller half, shifting away counted bytes. */
2796
    if ((v >> 32) != 0) { n += 4; v >>= 32; }
2797
    if ((v >> 16) != 0) { n += 2; v >>= 16; }
2798
    if ((v >>  8) != 0) { n += 1;           }
2799
2800
    /* The n value bytes big-endian then the length byte.  Enter the switch at
2801
     * case n and fall through, storing least-significant byte first into
2802
     * out[n-1]..out[0]. */
2803
    switch (n) {
2804
        case 8: out[7] = (byte)value; value >>= 8; FALL_THROUGH;
2805
        case 7: out[6] = (byte)value; value >>= 8; FALL_THROUGH;
2806
        case 6: out[5] = (byte)value; value >>= 8; FALL_THROUGH;
2807
        case 5: out[4] = (byte)value; value >>= 8; FALL_THROUGH;
2808
        case 4: out[3] = (byte)value; value >>= 8; FALL_THROUGH;
2809
        case 3: out[2] = (byte)value; value >>= 8; FALL_THROUGH;
2810
        case 2: out[1] = (byte)value; value >>= 8; FALL_THROUGH;
2811
        default: out[0] = (byte)value;
2812
    }
2813
    out[n] = (byte)n;
2814
2815
    return n + 1;
2816
}
2817
#endif /* WOLFSSL_KMAC */
2818
2819
/* Zero-pad the current bytepad() block, per NIST SP 800-185, section 2.3.3.
2820
 *
2821
 * Fills the tail of the current block with zeros so the number of bytes fed
2822
 * into the bytepad() block becomes a multiple of the KECCAK rate, then flushes
2823
 * the completed block.  The block offset is the sponge's own shake->i.
2824
 *
2825
 * @param [in,out] shake  SHAKE (KECCAK) object holding the sponge state.
2826
 * @param [in]     count  KECCAK 64-bit words per block - rate / 8.
2827
 * @param [in]     rate   KECCAK rate in bytes - the block size.
2828
 *
2829
 * @return  0 on success.
2830
 * @return  Negative error code from the sponge update on failure.
2831
 */
2832
static int CshakeBytePad(wc_Sha3* shake, word32 count, word32 rate)
2833
{
2834
    int    ret = 0;
2835
    word32 pad = (rate - shake->i) % rate;
2836
2837
    if (pad > 0) {
2838
        /* Zero the rest of the block in place and flush it - a zero-length
2839
         * update with i == rate triggers the XOR-in and permutation. */
2840
        XMEMSET(shake->t + shake->i, 0, pad);
2841
        shake->i = rate;
2842
        ret = Sha3Update(shake, shake->t, 0, count);
2843
    }
2844
    return ret;
2845
}
2846
2847
/* Absorb the leading customization block shared by cSHAKE and KMAC:
2848
 *   bytepad(encode_string(name) || encode_string(custom), rate)
2849
 * (NIST SP 800-185, sections 3.2 and 3.3).
2850
 *
2851
 * Only ever called right after Init, so the sponge is fresh (shake->i is 0
2852
 * and shake->t is all zero). When the whole bytepad content fits in one block
2853
 * (the common case) it is copied straight into the block buffer and flushed
2854
 * once; otherwise the parts that may cross a block boundary go through
2855
 * Sha3Update.
2856
 *
2857
 * @param [in,out] shake      SHAKE (KECCAK) object holding the sponge state.
2858
 * @param [in]     count      KECCAK 64-bit words per block - rate / 8.
2859
 * @param [in]     name       Function-name string, NULL when nameLen is 0.
2860
 * @param [in]     nameLen    Length of name in bytes.
2861
 * @param [in]     custom     Customization string, NULL when customLen is 0.
2862
 * @param [in]     customLen  Length of custom in bytes.
2863
 *
2864
 * @return  0 on success.
2865
 * @return  Negative error code from the sponge update on failure.
2866
 */
2867
static int CshakeAbsorbBlock(wc_Sha3* shake, word32 count, const byte* name,
2868
    word32 nameLen, const byte* custom, word32 customLen)
2869
{
2870
    word32 rate = count * 8U;
2871
    byte   enc[9];
2872
    word32 e;
2873
    word32 h;
2874
    word32 avail;
2875
    int    ret = 0;
2876
2877
    /* left_encode(rate) || left_encode(nameLen * 8) straight into the block
2878
     * buffer - fits at the start of a fresh block. */
2879
    h  = KmacLeftEncode(shake->t, (word64)rate);
2880
    h += KmacLeftEncode(shake->t + h, (word64)nameLen * 8);
2881
    e  = KmacLeftEncode(enc, (word64)customLen * 8);
2882
    avail = rate - h;
2883
2884
    /* Common case: the whole bytepad content fits in this one block, so copy
2885
     * name || left_encode(customLen*8) || custom straight in and let the pad
2886
     * flush it - no per-piece Sha3Update.  Conditions are ordered to avoid
2887
     * word32 overflow when name/custom are large. */
2888
    if ((nameLen < avail) && (e < avail - nameLen) &&
2889
            (customLen < avail - nameLen - e)) {
2890
        if (nameLen > 0) {
2891
            XMEMCPY(shake->t + h, name, nameLen);
2892
            h += nameLen;
2893
        }
2894
        XMEMCPY(shake->t + h, enc, e);
2895
        h += e;
2896
        if (customLen > 0) {
2897
            XMEMCPY(shake->t + h, custom, customLen);
2898
            h += customLen;
2899
        }
2900
        shake->i = h;
2901
    }
2902
    else {
2903
        /* name and/or custom cross a block boundary - absorb them. */
2904
        shake->i = h;
2905
        if (nameLen > 0) {
2906
            ret = Sha3Update(shake, name, nameLen, count);
2907
        }
2908
        if (ret == 0) {
2909
            ret = Sha3Update(shake, enc, e, count);
2910
        }
2911
        if ((ret == 0) && (customLen > 0)) {
2912
            ret = Sha3Update(shake, custom, customLen, count);
2913
        }
2914
    }
2915
2916
    /* bytepad zero-fill - shake->i already tracks the block offset. */
2917
    if (ret == 0) {
2918
        ret = CshakeBytePad(shake, count, rate);
2919
    }
2920
    return ret;
2921
}
2922
2923
#ifdef WOLFSSL_KMAC
2924
/* Initialize a KMAC operation for the given KECCAK block count.
2925
 *
2926
 * count is WC_SHA3_128_COUNT for KMAC128 or WC_SHA3_256_COUNT for KMAC256.
2927
 * Absorbs the two leading cSHAKE/KMAC bytepad blocks, leaving the sponge ready
2928
 * for message data (NIST SP 800-185, sections 3.2 and 4.3):
2929
 *   bytepad(encode_string("KMAC") || encode_string(custom), rate)
2930
 *   bytepad(encode_string(key), rate)
2931
 *
2932
 * @param [out] kmac       KMAC object to initialize.
2933
 * @param [in]  count      KECCAK 64-bit words per block - rate / 8.
2934
 * @param [in]  key        Key bytes.
2935
 * @param [in]  keyLen     Length of key in bytes.
2936
 * @param [in]  custom     Customization string, or NULL when customLen is 0.
2937
 * @param [in]  customLen  Length of custom in bytes.
2938
 * @param [in]  heap       Dynamic memory hint.
2939
 * @param [in]  devId      Device identifier.
2940
 *
2941
 * @return  0 on success.
2942
 * @return  BAD_FUNC_ARG when a NULL pointer has a non-zero length.
2943
 * @return  Negative error code from the sponge update on failure.
2944
 */
2945
static int KmacInit(wc_Kmac* kmac, word32 count, const byte* key, word32 keyLen,
2946
    const byte* custom, word32 customLen, void* heap, int devId)
2947
{
2948
    /* The KMAC function name string "KMAC". */
2949
    static const byte kmacName[4] = { 0x4b, 0x4d, 0x41, 0x43 };
2950
    word32 rate;
2951
    int    ret;
2952
2953
    if ((kmac == NULL) || ((key == NULL) && (keyLen != 0)) ||
2954
            ((custom == NULL) && (customLen != 0))) {
2955
        ret = BAD_FUNC_ARG;
2956
    }
2957
#ifdef HAVE_FIPS
2958
    else if (keyLen < KMAC_FIPS_MIN_KEY) {
2959
        ret = KMAC_MIN_KEYLEN_E;
2960
    }
2961
#endif
2962
    else {
2963
        kmac->count = count;
2964
        rate = count * 8U;
2965
        ret = wc_InitSha3(&kmac->shake, heap, devId);
2966
2967
        /* bytepad(encode_string("KMAC") || encode_string(custom), rate) */
2968
        if (ret == 0) {
2969
            ret = CshakeAbsorbBlock(&kmac->shake, count, kmacName,
2970
                (word32)sizeof(kmacName), custom, customLen);
2971
        }
2972
2973
        /* bytepad(encode_string(key), rate).  The block above flushed, so the
2974
         * sponge is at a block boundary (shake->i == 0) - write the length
2975
         * encodings straight into the block buffer, as in CshakeAbsorbBlock. */
2976
        if (ret == 0) {
2977
            word32 h;
2978
2979
            h  = KmacLeftEncode(kmac->shake.t, (word64)rate);
2980
            h += KmacLeftEncode(kmac->shake.t + h, (word64)keyLen * 8);
2981
            kmac->shake.i = h;
2982
2983
            if (keyLen > 0) {
2984
                /* Copy a key that fits into the block straight in and flush
2985
                 * once; a longer key crosses a boundary so is absorbed. */
2986
                if (keyLen < rate - h) {
2987
                    XMEMCPY(kmac->shake.t + h, key, keyLen);
2988
                    kmac->shake.i += keyLen;
2989
                }
2990
                else {
2991
                    ret = Sha3Update(&kmac->shake, key, keyLen, count);
2992
                }
2993
            }
2994
            if (ret == 0) {
2995
                ret = CshakeBytePad(&kmac->shake, count, rate);
2996
            }
2997
        }
2998
    }
2999
3000
    return ret;
3001
}
3002
3003
/* Absorb message data into a KMAC operation.
3004
 *
3005
 * @param [in,out] kmac   KMAC object holding the sponge state.
3006
 * @param [in]     in     Message bytes, or NULL when inLen is 0.
3007
 * @param [in]     inLen  Length of in in bytes.
3008
 *
3009
 * @return  0 on success.
3010
 * @return  BAD_FUNC_ARG on a NULL message with a non-zero length.
3011
 * @return  Negative error code from the sponge update on failure.
3012
 */
3013
static int KmacUpdate(wc_Kmac* kmac, const byte* in, word32 inLen)
3014
{
3015
    int ret;
3016
3017
    if ((kmac == NULL) || ((in == NULL) && (inLen != 0))) {
3018
        ret = BAD_FUNC_ARG;
3019
    }
3020
    else {
3021
        ret = Sha3Update(&kmac->shake, in, inLen, kmac->count);
3022
    }
3023
    return ret;
3024
}
3025
3026
/* Finalize a KMAC operation, producing outLen bytes of output.
3027
 *
3028
 * For fixed-length KMAC (xof == 0) the requested length is encoded into the
3029
 * message (right_encode(outLen * 8)) before the cSHAKE pad, so changing outLen
3030
 * changes the whole result - as required by SP 800-185. For the XOF variant
3031
 * (xof != 0) right_encode(0) is used and any number of output bytes may be
3032
 * produced without changing the leading bytes.
3033
 *
3034
 * @param [in,out] kmac    KMAC object holding the sponge state.
3035
 * @param [out]    out     Buffer to hold output.
3036
 * @param [in]     outLen  Number of output bytes to produce.
3037
 * @param [in]     xof     Non-zero to finalize as an XOF - encode length 0.
3038
 *
3039
 * @return  0 on success.
3040
 * @return  BAD_FUNC_ARG when kmac or out is NULL.
3041
 * @return  Negative error code from the sponge on failure.
3042
 */
3043
static int KmacFinal(wc_Kmac* kmac, byte* out, word32 outLen, int xof)
3044
{
3045
    word32 rate;
3046
    int    ret = 0;
3047
3048
    if ((kmac == NULL) || (out == NULL)) {
3049
        ret = BAD_FUNC_ARG;
3050
    }
3051
#ifdef HAVE_FIPS
3052
    else if ((xof == 0) && (outLen < KMAC_FIPS_MIN_OUTPUT)) {
3053
        ret = BAD_LENGTH_E;
3054
    }
3055
#endif
3056
    else if ((kmac->count < WC_SHA3_512_COUNT) ||
3057
             (kmac->count > WC_SHA3_128_COUNT) ||
3058
             (kmac->shake.i >= kmac->count * 8U)) {
3059
        ret = BAD_STATE_E;
3060
    }
3061
    else {
3062
        /* right_encode(outLen * 8), or right_encode(0) for the XOF. */
3063
        word64 v = xof ? (word64)0 : (word64)outLen * 8;
3064
        rate = kmac->count * 8U;
3065
3066
        /* The encoding is at most 9 bytes; when that many fit in the current
3067
         * block, write it straight into the block buffer, otherwise use a
3068
         * temporary and Sha3Update (which handles crossing the boundary). */
3069
        if (kmac->shake.i + 9 < rate) {
3070
            word32 l = KmacRightEncode(kmac->shake.t + kmac->shake.i, v);
3071
            kmac->shake.i += l;
3072
        }
3073
        else {
3074
            byte   enc[9];
3075
            word32 encLen = KmacRightEncode(enc, v);
3076
            ret = Sha3Update(&kmac->shake, enc, encLen, kmac->count);
3077
        }
3078
        if (ret == 0) {
3079
            /* cSHAKE domain separation pad (0x04), then squeeze outLen. */
3080
            ret = Sha3Final(&kmac->shake, 0x04, out, kmac->count, outLen);
3081
        }
3082
    }
3083
    return ret;
3084
}
3085
3086
/* Copy the state of a KMAC operation so it can be finalized more than once
3087
 * (for example over a common prefix).
3088
 *
3089
 * dst must be an initialized wc_Kmac: the copy releases any resources it
3090
 * already holds before overwriting it (as with wc_Sha3Copy/wc_Shake_Copy).
3091
 *
3092
 * @param [in]  src  KMAC object to copy from.
3093
 * @param [out] dst  Initialized KMAC object to copy into.
3094
 *
3095
 * @return  0 on success.
3096
 * @return  BAD_FUNC_ARG when src or dst is NULL.
3097
 * @return  Negative error code from the sponge copy on failure.
3098
 */
3099
static int KmacCopy(wc_Kmac* src, wc_Kmac* dst)
3100
{
3101
    int ret;
3102
3103
    if ((src == NULL) || (dst == NULL)) {
3104
        ret = BAD_FUNC_ARG;
3105
    }
3106
    else {
3107
        ret = wc_Sha3Copy(&src->shake, &dst->shake);
3108
        if (ret == 0) {
3109
            dst->count = src->count;
3110
        }
3111
    }
3112
    return ret;
3113
}
3114
#endif /* WOLFSSL_KMAC */
3115
3116
#if defined(WOLFSSL_CSHAKE128) || defined(WOLFSSL_CSHAKE256)
3117
/* Initialize a cSHAKE operation for the given KECCAK block count.
3118
 *
3119
 * count is WC_SHA3_128_COUNT for cSHAKE128 or WC_SHA3_256_COUNT for cSHAKE256.
3120
 * When both the function-name and customization strings are empty, cSHAKE is
3121
 * defined to reduce to plain SHAKE (NIST SP 800-185, section 3.3), so no
3122
 * customization block is absorbed and the SHAKE pad (0x1f) is used.
3123
 *
3124
 * @param [out] cshake     cSHAKE object to initialize.
3125
 * @param [in]  count      KECCAK 64-bit words per block - rate / 8.
3126
 * @param [in]  name       Function-name string, or NULL when nameLen is 0.
3127
 * @param [in]  nameLen    Length of name in bytes.
3128
 * @param [in]  custom     Customization string, or NULL when customLen is 0.
3129
 * @param [in]  customLen  Length of custom in bytes.
3130
 * @param [in]  heap       Dynamic memory hint.
3131
 * @param [in]  devId      Device identifier.
3132
 *
3133
 * @return  0 on success.
3134
 * @return  BAD_FUNC_ARG when a NULL pointer has a non-zero length.
3135
 * @return  Negative error code from the sponge update on failure.
3136
 */
3137
static int CshakeInit(wc_Cshake* cshake, word32 count, const byte* name,
3138
    word32 nameLen, const byte* custom, word32 customLen, void* heap, int devId)
3139
{
3140
    int ret;
3141
3142
    if ((cshake == NULL) || ((name == NULL) && (nameLen != 0)) ||
3143
            ((custom == NULL) && (customLen != 0))) {
3144
        ret = BAD_FUNC_ARG;
3145
    }
3146
    else {
3147
        cshake->count = count;
3148
        ret = wc_InitSha3(&cshake->shake, heap, devId);
3149
        if (ret == 0) {
3150
            if ((nameLen == 0) && (customLen == 0)) {
3151
                /* No customization: cSHAKE reduces to SHAKE. */
3152
                cshake->pad = 0x1f;
3153
            }
3154
            else {
3155
                cshake->pad = 0x04;
3156
                ret = CshakeAbsorbBlock(&cshake->shake, count, name, nameLen,
3157
                    custom, customLen);
3158
            }
3159
        }
3160
    }
3161
    return ret;
3162
}
3163
3164
/* Absorb message data into a cSHAKE operation.
3165
 *
3166
 * @param [in,out] cshake  cSHAKE object holding the sponge state.
3167
 * @param [in]     in      Message bytes, or NULL when inLen is 0.
3168
 * @param [in]     inLen   Length of in in bytes.
3169
 *
3170
 * @return  0 on success.
3171
 * @return  BAD_FUNC_ARG on a NULL message with a non-zero length.
3172
 * @return  Negative error code from the sponge update on failure.
3173
 */
3174
static int CshakeUpdate(wc_Cshake* cshake, const byte* in, word32 inLen)
3175
{
3176
    int ret;
3177
3178
    if ((cshake == NULL) || ((in == NULL) && (inLen != 0))) {
3179
        ret = BAD_FUNC_ARG;
3180
    }
3181
    else {
3182
        ret = Sha3Update(&cshake->shake, in, inLen, cshake->count);
3183
    }
3184
    return ret;
3185
}
3186
3187
/* Finalize a cSHAKE operation, squeezing outLen bytes. cSHAKE is an XOF, so
3188
 * the output length is not bound into the result and a longer squeeze extends
3189
 * a shorter one.
3190
 *
3191
 * @param [in,out] cshake  cSHAKE object holding the sponge state.
3192
 * @param [out]    out     Buffer to hold output.
3193
 * @param [in]     outLen  Number of output bytes to produce.
3194
 *
3195
 * @return  0 on success.
3196
 * @return  BAD_FUNC_ARG when cshake or out is NULL.
3197
 * @return  Negative error code from the sponge on failure.
3198
 */
3199
static int CshakeFinal(wc_Cshake* cshake, byte* out, word32 outLen)
3200
{
3201
    int ret;
3202
3203
    if ((cshake == NULL) || (out == NULL)) {
3204
        ret = BAD_FUNC_ARG;
3205
    }
3206
    else {
3207
        ret = Sha3Final(&cshake->shake, cshake->pad, out, cshake->count,
3208
            outLen);
3209
    }
3210
    return ret;
3211
}
3212
3213
/* Copy the state of a cSHAKE operation so it can be finalized more than once
3214
 * (for example over a common message prefix).
3215
 *
3216
 * dst must be an initialized wc_Cshake: the copy releases any resources it
3217
 * already holds before overwriting it (as with wc_Sha3Copy/wc_Shake_Copy).
3218
 *
3219
 * @param [in]  src  cSHAKE object to copy from.
3220
 * @param [out] dst  Initialized cSHAKE object to copy into.
3221
 *
3222
 * @return  0 on success.
3223
 * @return  BAD_FUNC_ARG when src or dst is NULL.
3224
 * @return  Negative error code from the sponge copy on failure.
3225
 */
3226
static int CshakeCopy(wc_Cshake* src, wc_Cshake* dst)
3227
{
3228
    int ret;
3229
3230
    if ((src == NULL) || (dst == NULL)) {
3231
        ret = BAD_FUNC_ARG;
3232
    }
3233
    else {
3234
        ret = wc_Sha3Copy(&src->shake, &dst->shake);
3235
        if (ret == 0) {
3236
            dst->count = src->count;
3237
            dst->pad   = src->pad;
3238
        }
3239
    }
3240
    return ret;
3241
}
3242
#endif /* WOLFSSL_CSHAKE128 || WOLFSSL_CSHAKE256 */
3243
3244
#ifdef WOLFSSL_KMAC128
3245
/* Initialize a KMAC128 operation with a key and optional customization string.
3246
 *
3247
 * @param [out] kmac       wc_Kmac object to initialize.
3248
 * @param [in]  key        Key bytes.
3249
 * @param [in]  keyLen     Length of the key in bytes.
3250
 * @param [in]  custom     Customization string, or NULL when customLen is 0.
3251
 * @param [in]  customLen  Length of the customization string in bytes.
3252
 * @param [in]  heap       Dynamic memory hint.
3253
 * @param [in]  devId      Device identifier.
3254
 *
3255
 * @return  0 on success.
3256
 * @return  BAD_FUNC_ARG when a required pointer is NULL.
3257
 */
3258
int wc_InitKmac128(wc_Kmac* kmac, const byte* key, word32 keyLen,
3259
    const byte* custom, word32 customLen, void* heap, int devId)
3260
{
3261
    return KmacInit(kmac, WC_SHA3_128_COUNT, key, keyLen, custom, customLen,
3262
        heap, devId);
3263
}
3264
3265
/* Absorb message data into a KMAC128 operation.
3266
 *
3267
 * @param [in,out] kmac   wc_Kmac object holding state.
3268
 * @param [in]     in     Message bytes, or NULL when inLen is 0.
3269
 * @param [in]     inLen  Length of in in bytes.
3270
 *
3271
 * @return  0 on success.
3272
 * @return  BAD_FUNC_ARG on a NULL message with a non-zero length.
3273
 */
3274
int wc_Kmac128_Update(wc_Kmac* kmac, const byte* in, word32 inLen)
3275
{
3276
    return KmacUpdate(kmac, in, inLen);
3277
}
3278
3279
/* Finalize a KMAC128 operation, writing outLen bytes to out.
3280
 *
3281
 * The output length is bound into the result (NIST SP 800-185 KMAC).
3282
 *
3283
 * @param [in,out] kmac    wc_Kmac object holding state.
3284
 * @param [out]    out     Buffer to hold the output.
3285
 * @param [in]     outLen  Number of output bytes to produce.
3286
 *
3287
 * @return  0 on success.
3288
 * @return  BAD_FUNC_ARG when a parameter is NULL.
3289
 */
3290
int wc_Kmac128_Final(wc_Kmac* kmac, byte* out, word32 outLen)
3291
{
3292
    return KmacFinal(kmac, out, outLen, 0);
3293
}
3294
3295
/* Finalize a KMAC128 operation as an XOF - KMACXOF128.
3296
 *
3297
 * The output length is not bound into the result, so any amount of output may
3298
 * be requested.
3299
 *
3300
 * @param [in,out] kmac    wc_Kmac object holding state.
3301
 * @param [out]    out     Buffer to hold the output.
3302
 * @param [in]     outLen  Number of output bytes to produce.
3303
 *
3304
 * @return  0 on success.
3305
 * @return  BAD_FUNC_ARG when a parameter is NULL.
3306
 */
3307
int wc_Kmac128_FinalXof(wc_Kmac* kmac, byte* out, word32 outLen)
3308
{
3309
    return KmacFinal(kmac, out, outLen, 1);
3310
}
3311
3312
/* Copy the state of a KMAC128 operation, allowing it to be finalized more
3313
 * than once (for example over a common message prefix).
3314
 *
3315
 * @param [in]  src  wc_Kmac object to copy from.
3316
 * @param [out] dst  wc_Kmac object to copy into.
3317
 *
3318
 * @return  0 on success.
3319
 * @return  BAD_FUNC_ARG when src or dst is NULL.
3320
 */
3321
int wc_Kmac128_Copy(wc_Kmac* src, wc_Kmac* dst)
3322
{
3323
    return KmacCopy(src, dst);
3324
}
3325
3326
/* Dispose of any dynamically allocated data from a KMAC128 operation.
3327
 *
3328
 * The sponge state is key-derived, so it is zeroized on free, as with the
3329
 * other keyed MACs, HMAC and CMAC.
3330
 *
3331
 * @param [in,out] kmac  wc_Kmac object to free. May be NULL.
3332
 */
3333
void wc_Kmac128_Free(wc_Kmac* kmac)
3334
{
3335
    if (kmac != NULL) {
3336
        wc_Sha3Free(&kmac->shake);
3337
        ForceZero(kmac, sizeof(*kmac));
3338
    }
3339
}
3340
3341
/* One-shot KMAC128 over a single message.
3342
 *
3343
 * @param [in]  key        Key bytes.
3344
 * @param [in]  keyLen     Length of the key in bytes.
3345
 * @param [in]  custom     Customization string, or NULL when customLen is 0.
3346
 * @param [in]  customLen  Length of the customization string in bytes.
3347
 * @param [in]  in         Message bytes, or NULL when inLen is 0.
3348
 * @param [in]  inLen      Length of the message in bytes.
3349
 * @param [out] out        Buffer to hold the output.
3350
 * @param [in]  outLen     Number of output bytes to produce.
3351
 *
3352
 * @return  0 on success.
3353
 * @return  Negative error code on failure.
3354
 */
3355
int wc_Kmac128Hash(const byte* key, word32 keyLen, const byte* custom,
3356
    word32 customLen, const byte* in, word32 inLen, byte* out, word32 outLen)
3357
{
3358
    int ret = 0;
3359
    /* Heap-allocate the state on small-stack builds (it is ~400 bytes). */
3360
    WC_DECLARE_VAR(kmac, wc_Kmac, 1, NULL);
3361
3362
    WC_ALLOC_VAR_EX(kmac, wc_Kmac, 1, NULL, DYNAMIC_TYPE_TMP_BUFFER,
3363
        ret = MEMORY_E);
3364
3365
    if (ret == 0) {
3366
        ret = wc_InitKmac128(kmac, key, keyLen, custom, customLen, NULL,
3367
            INVALID_DEVID);
3368
    }
3369
    if (ret == 0) {
3370
        ret = wc_Kmac128_Update(kmac, in, inLen);
3371
    }
3372
    if (ret == 0) {
3373
        ret = wc_Kmac128_Final(kmac, out, outLen);
3374
    }
3375
    /* wc_Kmac128_Free tolerates a NULL pointer (allocation failure). */
3376
    wc_Kmac128_Free(kmac);
3377
    WC_FREE_VAR_EX(kmac, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3378
3379
    return ret;
3380
}
3381
3382
/* One-shot KMACXOF128 over a single message.
3383
 *
3384
 * As wc_Kmac128Hash(), but the output length is not bound into the result
3385
 * (KMACXOF128), so any amount of output may be requested.
3386
 *
3387
 * @param [in]  key        Key bytes.
3388
 * @param [in]  keyLen     Length of the key in bytes.
3389
 * @param [in]  custom     Customization string, or NULL when customLen is 0.
3390
 * @param [in]  customLen  Length of the customization string in bytes.
3391
 * @param [in]  in         Message bytes, or NULL when inLen is 0.
3392
 * @param [in]  inLen      Length of the message in bytes.
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  Negative error code on failure.
3398
 */
3399
int wc_Kmac128HashXof(const byte* key, word32 keyLen, const byte* custom,
3400
    word32 customLen, const byte* in, word32 inLen, byte* out, word32 outLen)
3401
{
3402
    int ret = 0;
3403
    /* Heap-allocate the state on small-stack builds (it is ~400 bytes). */
3404
    WC_DECLARE_VAR(kmac, wc_Kmac, 1, NULL);
3405
3406
    WC_ALLOC_VAR_EX(kmac, wc_Kmac, 1, NULL, DYNAMIC_TYPE_TMP_BUFFER,
3407
        ret = MEMORY_E);
3408
3409
    if (ret == 0) {
3410
        ret = wc_InitKmac128(kmac, key, keyLen, custom, customLen, NULL,
3411
            INVALID_DEVID);
3412
    }
3413
    if (ret == 0) {
3414
        ret = wc_Kmac128_Update(kmac, in, inLen);
3415
    }
3416
    if (ret == 0) {
3417
        ret = wc_Kmac128_FinalXof(kmac, out, outLen);
3418
    }
3419
    /* wc_Kmac128_Free tolerates a NULL pointer (allocation failure). */
3420
    wc_Kmac128_Free(kmac);
3421
    WC_FREE_VAR_EX(kmac, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3422
3423
    return ret;
3424
}
3425
#endif /* WOLFSSL_KMAC128 */
3426
3427
#ifdef WOLFSSL_KMAC256
3428
/* Initialize a KMAC256 operation with a key and optional customization string.
3429
 *
3430
 * @param [out] kmac       wc_Kmac object to initialize.
3431
 * @param [in]  key        Key bytes.
3432
 * @param [in]  keyLen     Length of the key in bytes.
3433
 * @param [in]  custom     Customization string, or NULL when customLen is 0.
3434
 * @param [in]  customLen  Length of the customization string in bytes.
3435
 * @param [in]  heap       Dynamic memory hint.
3436
 * @param [in]  devId      Device identifier.
3437
 *
3438
 * @return  0 on success.
3439
 * @return  BAD_FUNC_ARG when a required pointer is NULL.
3440
 */
3441
int wc_InitKmac256(wc_Kmac* kmac, const byte* key, word32 keyLen,
3442
    const byte* custom, word32 customLen, void* heap, int devId)
3443
{
3444
    return KmacInit(kmac, WC_SHA3_256_COUNT, key, keyLen, custom, customLen,
3445
        heap, devId);
3446
}
3447
3448
/* Absorb message data into a KMAC256 operation.
3449
 *
3450
 * @param [in,out] kmac   wc_Kmac object holding state.
3451
 * @param [in]     in     Message bytes, or NULL when inLen is 0.
3452
 * @param [in]     inLen  Length of in in bytes.
3453
 *
3454
 * @return  0 on success.
3455
 * @return  BAD_FUNC_ARG on a NULL message with a non-zero length.
3456
 */
3457
int wc_Kmac256_Update(wc_Kmac* kmac, const byte* in, word32 inLen)
3458
{
3459
    return KmacUpdate(kmac, in, inLen);
3460
}
3461
3462
/* Finalize a KMAC256 operation, writing outLen bytes to out.
3463
 *
3464
 * The output length is bound into the result (NIST SP 800-185 KMAC).
3465
 *
3466
 * @param [in,out] kmac    wc_Kmac object holding state.
3467
 * @param [out]    out     Buffer to hold the output.
3468
 * @param [in]     outLen  Number of output bytes to produce.
3469
 *
3470
 * @return  0 on success.
3471
 * @return  BAD_FUNC_ARG when a parameter is NULL.
3472
 */
3473
int wc_Kmac256_Final(wc_Kmac* kmac, byte* out, word32 outLen)
3474
{
3475
    return KmacFinal(kmac, out, outLen, 0);
3476
}
3477
3478
/* Finalize a KMAC256 operation as an XOF - KMACXOF256.
3479
 *
3480
 * The output length is not bound into the result, so any amount of output may
3481
 * be requested.
3482
 *
3483
 * @param [in,out] kmac    wc_Kmac object holding state.
3484
 * @param [out]    out     Buffer to hold the output.
3485
 * @param [in]     outLen  Number of output bytes to produce.
3486
 *
3487
 * @return  0 on success.
3488
 * @return  BAD_FUNC_ARG when a parameter is NULL.
3489
 */
3490
int wc_Kmac256_FinalXof(wc_Kmac* kmac, byte* out, word32 outLen)
3491
{
3492
    return KmacFinal(kmac, out, outLen, 1);
3493
}
3494
3495
/* Copy the state of a KMAC256 operation, allowing it to be finalized more
3496
 * than once (for example over a common message prefix).
3497
 *
3498
 * @param [in]  src  wc_Kmac object to copy from.
3499
 * @param [out] dst  wc_Kmac object to copy into.
3500
 *
3501
 * @return  0 on success.
3502
 * @return  BAD_FUNC_ARG when src or dst is NULL.
3503
 */
3504
int wc_Kmac256_Copy(wc_Kmac* src, wc_Kmac* dst)
3505
{
3506
    return KmacCopy(src, dst);
3507
}
3508
3509
/* Dispose of any dynamically allocated data from a KMAC256 operation.
3510
 *
3511
 * The sponge state is key-derived, so it is zeroized on free, as with the
3512
 * other keyed MACs, HMAC and CMAC.
3513
 *
3514
 * @param [in,out] kmac  wc_Kmac object to free. May be NULL.
3515
 */
3516
void wc_Kmac256_Free(wc_Kmac* kmac)
3517
{
3518
    if (kmac != NULL) {
3519
        wc_Sha3Free(&kmac->shake);
3520
        ForceZero(kmac, sizeof(*kmac));
3521
    }
3522
}
3523
3524
/* One-shot KMAC256 over a single message.
3525
 *
3526
 * @param [in]  key        Key bytes.
3527
 * @param [in]  keyLen     Length of the key 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]  in         Message bytes, or NULL when inLen is 0.
3531
 * @param [in]  inLen      Length of the message in bytes.
3532
 * @param [out] out        Buffer to hold the output.
3533
 * @param [in]  outLen     Number of output bytes to produce.
3534
 *
3535
 * @return  0 on success.
3536
 * @return  Negative error code on failure.
3537
 */
3538
int wc_Kmac256Hash(const byte* key, word32 keyLen, const byte* custom,
3539
    word32 customLen, const byte* in, word32 inLen, byte* out, word32 outLen)
3540
{
3541
    int ret = 0;
3542
    /* Heap-allocate the state on small-stack builds (it is ~400 bytes). */
3543
    WC_DECLARE_VAR(kmac, wc_Kmac, 1, NULL);
3544
3545
    WC_ALLOC_VAR_EX(kmac, wc_Kmac, 1, NULL, DYNAMIC_TYPE_TMP_BUFFER,
3546
        ret = MEMORY_E);
3547
3548
    if (ret == 0) {
3549
        ret = wc_InitKmac256(kmac, key, keyLen, custom, customLen, NULL,
3550
            INVALID_DEVID);
3551
    }
3552
    if (ret == 0) {
3553
        ret = wc_Kmac256_Update(kmac, in, inLen);
3554
    }
3555
    if (ret == 0) {
3556
        ret = wc_Kmac256_Final(kmac, out, outLen);
3557
    }
3558
    /* wc_Kmac256_Free tolerates a NULL pointer (allocation failure). */
3559
    wc_Kmac256_Free(kmac);
3560
    WC_FREE_VAR_EX(kmac, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3561
3562
    return ret;
3563
}
3564
3565
/* One-shot KMACXOF256 over a single message.
3566
 *
3567
 * As wc_Kmac256Hash(), but the output length is not bound into the result
3568
 * (KMACXOF256), so any amount of output may be requested.
3569
 *
3570
 * @param [in]  key        Key bytes.
3571
 * @param [in]  keyLen     Length of the key in bytes.
3572
 * @param [in]  custom     Customization string, or NULL when customLen is 0.
3573
 * @param [in]  customLen  Length of the customization string in bytes.
3574
 * @param [in]  in         Message bytes, or NULL when inLen is 0.
3575
 * @param [in]  inLen      Length of the message in bytes.
3576
 * @param [out] out        Buffer to hold the output.
3577
 * @param [in]  outLen     Number of output bytes to produce.
3578
 *
3579
 * @return  0 on success.
3580
 * @return  Negative error code on failure.
3581
 */
3582
int wc_Kmac256HashXof(const byte* key, word32 keyLen, const byte* custom,
3583
    word32 customLen, const byte* in, word32 inLen, byte* out, word32 outLen)
3584
{
3585
    int ret = 0;
3586
    /* Heap-allocate the state on small-stack builds (it is ~400 bytes). */
3587
    WC_DECLARE_VAR(kmac, wc_Kmac, 1, NULL);
3588
3589
    WC_ALLOC_VAR_EX(kmac, wc_Kmac, 1, NULL, DYNAMIC_TYPE_TMP_BUFFER,
3590
        ret = MEMORY_E);
3591
3592
    if (ret == 0) {
3593
        ret = wc_InitKmac256(kmac, key, keyLen, custom, customLen, NULL,
3594
            INVALID_DEVID);
3595
    }
3596
    if (ret == 0) {
3597
        ret = wc_Kmac256_Update(kmac, in, inLen);
3598
    }
3599
    if (ret == 0) {
3600
        ret = wc_Kmac256_FinalXof(kmac, out, outLen);
3601
    }
3602
    /* wc_Kmac256_Free tolerates a NULL pointer (allocation failure). */
3603
    wc_Kmac256_Free(kmac);
3604
    WC_FREE_VAR_EX(kmac, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3605
3606
    return ret;
3607
}
3608
#endif /* WOLFSSL_KMAC256 */
3609
3610
#ifdef WOLFSSL_CSHAKE128
3611
/* Initialize a cSHAKE128 operation with a function-name and customization
3612
 * string (NIST SP 800-185). Enabled together with KMAC (WOLFSSL_KMAC).
3613
 *
3614
 * @param [out] cshake     wc_Cshake object to initialize.
3615
 * @param [in]  name       Function-name string, or NULL when nameLen is 0.
3616
 *                         Reserved for NIST-defined functions; use an empty
3617
 *                         string for application customization via custom.
3618
 * @param [in]  nameLen    Length of name in bytes.
3619
 * @param [in]  custom     Customization string, or NULL when customLen is 0.
3620
 * @param [in]  customLen  Length of the customization string in bytes.
3621
 * @param [in]  heap       Dynamic memory hint.
3622
 * @param [in]  devId      Device identifier.
3623
 *
3624
 * @return  0 on success.
3625
 * @return  BAD_FUNC_ARG when a required pointer is NULL.
3626
 */
3627
int wc_InitCshake128(wc_Cshake* cshake, const byte* name, word32 nameLen,
3628
    const byte* custom, word32 customLen, void* heap, int devId)
3629
{
3630
    return CshakeInit(cshake, WC_SHA3_128_COUNT, name, nameLen, custom,
3631
        customLen, heap, devId);
3632
}
3633
3634
/* Absorb message data into a cSHAKE128 operation.
3635
 *
3636
 * @param [in,out] cshake  wc_Cshake object holding state.
3637
 * @param [in]     in      Message bytes, or NULL when inLen is 0.
3638
 * @param [in]     inLen   Length of in in bytes.
3639
 *
3640
 * @return  0 on success.
3641
 * @return  BAD_FUNC_ARG on a NULL message with a non-zero length.
3642
 */
3643
int wc_Cshake128_Update(wc_Cshake* cshake, const byte* in, word32 inLen)
3644
{
3645
    return CshakeUpdate(cshake, in, inLen);
3646
}
3647
3648
/* Finalize a cSHAKE128 operation, writing outLen bytes to out.
3649
 *
3650
 * @param [in,out] cshake  wc_Cshake object holding state.
3651
 * @param [out]    out     Buffer to hold the output.
3652
 * @param [in]     outLen  Number of output bytes to produce.
3653
 *
3654
 * @return  0 on success.
3655
 * @return  BAD_FUNC_ARG when a parameter is NULL.
3656
 */
3657
int wc_Cshake128_Final(wc_Cshake* cshake, byte* out, word32 outLen)
3658
{
3659
    return CshakeFinal(cshake, out, outLen);
3660
}
3661
3662
/* Copy the state of a cSHAKE128 operation, allowing it to be finalized more
3663
 * than once (for example over a common message prefix). dst must already be
3664
 * an initialized wc_Cshake.
3665
 *
3666
 * @param [in]  src  wc_Cshake object to copy from.
3667
 * @param [out] dst  wc_Cshake object to copy into.
3668
 *
3669
 * @return  0 on success.
3670
 * @return  BAD_FUNC_ARG when src or dst is NULL.
3671
 */
3672
int wc_Cshake128_Copy(wc_Cshake* src, wc_Cshake* dst)
3673
{
3674
    return CshakeCopy(src, dst);
3675
}
3676
3677
/* Dispose of any dynamically allocated data from a cSHAKE128 operation.
3678
 *
3679
 * @param [in,out] cshake  wc_Cshake object to free. May be NULL.
3680
 */
3681
void wc_Cshake128_Free(wc_Cshake* cshake)
3682
{
3683
    if (cshake != NULL) {
3684
        wc_Sha3Free(&cshake->shake);
3685
    }
3686
}
3687
3688
/* One-shot cSHAKE128 over a single message.
3689
 *
3690
 * @param [in]  name       Function-name string, or NULL when nameLen is 0.
3691
 * @param [in]  nameLen    Length of name in bytes.
3692
 * @param [in]  custom     Customization string, or NULL when customLen is 0.
3693
 * @param [in]  customLen  Length of the customization string in bytes.
3694
 * @param [in]  in         Message bytes, or NULL when inLen is 0.
3695
 * @param [in]  inLen      Length of the message in bytes.
3696
 * @param [out] out        Buffer to hold the output.
3697
 * @param [in]  outLen     Number of output bytes to produce.
3698
 *
3699
 * @return  0 on success.
3700
 * @return  Negative error code on failure.
3701
 */
3702
int wc_Cshake128(const byte* name, word32 nameLen, const byte* custom,
3703
    word32 customLen, const byte* in, word32 inLen, byte* out, word32 outLen)
3704
{
3705
    int ret = 0;
3706
    /* Heap-allocate the state on small-stack builds (it is ~400 bytes). */
3707
    WC_DECLARE_VAR(cshake, wc_Cshake, 1, NULL);
3708
3709
    WC_ALLOC_VAR_EX(cshake, wc_Cshake, 1, NULL, DYNAMIC_TYPE_TMP_BUFFER,
3710
        ret = MEMORY_E);
3711
3712
    if (ret == 0) {
3713
        ret = wc_InitCshake128(cshake, name, nameLen, custom, customLen, NULL,
3714
            INVALID_DEVID);
3715
    }
3716
    if (ret == 0) {
3717
        ret = wc_Cshake128_Update(cshake, in, inLen);
3718
    }
3719
    if (ret == 0) {
3720
        ret = wc_Cshake128_Final(cshake, out, outLen);
3721
    }
3722
    /* wc_Cshake128_Free tolerates a NULL pointer (allocation failure). */
3723
    wc_Cshake128_Free(cshake);
3724
    WC_FREE_VAR_EX(cshake, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3725
3726
    return ret;
3727
}
3728
#endif /* WOLFSSL_CSHAKE128 */
3729
3730
#ifdef WOLFSSL_CSHAKE256
3731
/* Initialize a cSHAKE256 operation with a function-name and customization
3732
 * string. See wc_InitCshake128() for parameter details.
3733
 *
3734
 * @param [out] cshake     wc_Cshake object to initialize.
3735
 * @param [in]  name       Function-name string, or NULL when nameLen is 0.
3736
 * @param [in]  nameLen    Length of name in bytes.
3737
 * @param [in]  custom     Customization string, or NULL when customLen is 0.
3738
 * @param [in]  customLen  Length of the customization string in bytes.
3739
 * @param [in]  heap       Dynamic memory hint.
3740
 * @param [in]  devId      Device identifier.
3741
 *
3742
 * @return  0 on success.
3743
 * @return  BAD_FUNC_ARG when a required pointer is NULL.
3744
 */
3745
int wc_InitCshake256(wc_Cshake* cshake, const byte* name, word32 nameLen,
3746
    const byte* custom, word32 customLen, void* heap, int devId)
3747
{
3748
    return CshakeInit(cshake, WC_SHA3_256_COUNT, name, nameLen, custom,
3749
        customLen, heap, devId);
3750
}
3751
3752
/* Absorb message data into a cSHAKE256 operation.
3753
 *
3754
 * @param [in,out] cshake  wc_Cshake object holding state.
3755
 * @param [in]     in      Message bytes, or NULL when inLen is 0.
3756
 * @param [in]     inLen   Length of in in bytes.
3757
 *
3758
 * @return  0 on success.
3759
 * @return  BAD_FUNC_ARG on a NULL message with a non-zero length.
3760
 */
3761
int wc_Cshake256_Update(wc_Cshake* cshake, const byte* in, word32 inLen)
3762
{
3763
    return CshakeUpdate(cshake, in, inLen);
3764
}
3765
3766
/* Finalize a cSHAKE256 operation, writing outLen bytes to out.
3767
 *
3768
 * @param [in,out] cshake  wc_Cshake object holding state.
3769
 * @param [out]    out     Buffer to hold the output.
3770
 * @param [in]     outLen  Number of output bytes to produce.
3771
 *
3772
 * @return  0 on success.
3773
 * @return  BAD_FUNC_ARG when a parameter is NULL.
3774
 */
3775
int wc_Cshake256_Final(wc_Cshake* cshake, byte* out, word32 outLen)
3776
{
3777
    return CshakeFinal(cshake, out, outLen);
3778
}
3779
3780
/* Copy the state of a cSHAKE256 operation, allowing it to be finalized more
3781
 * than once (for example over a common message prefix). dst must already be
3782
 * an initialized wc_Cshake.
3783
 *
3784
 * @param [in]  src  wc_Cshake object to copy from.
3785
 * @param [out] dst  wc_Cshake object to copy into.
3786
 *
3787
 * @return  0 on success.
3788
 * @return  BAD_FUNC_ARG when src or dst is NULL.
3789
 */
3790
int wc_Cshake256_Copy(wc_Cshake* src, wc_Cshake* dst)
3791
{
3792
    return CshakeCopy(src, dst);
3793
}
3794
3795
/* Dispose of any dynamically allocated data from a cSHAKE256 operation.
3796
 *
3797
 * @param [in,out] cshake  wc_Cshake object to free. May be NULL.
3798
 */
3799
void wc_Cshake256_Free(wc_Cshake* cshake)
3800
{
3801
    if (cshake != NULL) {
3802
        wc_Sha3Free(&cshake->shake);
3803
    }
3804
}
3805
3806
/* One-shot cSHAKE256 over a single message. See wc_Cshake128() for details.
3807
 *
3808
 * @param [in]  name       Function-name string, or NULL when nameLen is 0.
3809
 * @param [in]  nameLen    Length of name in bytes.
3810
 * @param [in]  custom     Customization string, or NULL when customLen is 0.
3811
 * @param [in]  customLen  Length of the customization string in bytes.
3812
 * @param [in]  in         Message bytes, or NULL when inLen is 0.
3813
 * @param [in]  inLen      Length of the message in bytes.
3814
 * @param [out] out        Buffer to hold the output.
3815
 * @param [in]  outLen     Number of output bytes to produce.
3816
 *
3817
 * @return  0 on success.
3818
 * @return  Negative error code on failure.
3819
 */
3820
int wc_Cshake256(const byte* name, word32 nameLen, const byte* custom,
3821
    word32 customLen, const byte* in, word32 inLen, byte* out, word32 outLen)
3822
{
3823
    int ret = 0;
3824
    /* Heap-allocate the state on small-stack builds (it is ~400 bytes). */
3825
    WC_DECLARE_VAR(cshake, wc_Cshake, 1, NULL);
3826
3827
    WC_ALLOC_VAR_EX(cshake, wc_Cshake, 1, NULL, DYNAMIC_TYPE_TMP_BUFFER,
3828
        ret = MEMORY_E);
3829
3830
    if (ret == 0) {
3831
        ret = wc_InitCshake256(cshake, name, nameLen, custom, customLen, NULL,
3832
            INVALID_DEVID);
3833
    }
3834
    if (ret == 0) {
3835
        ret = wc_Cshake256_Update(cshake, in, inLen);
3836
    }
3837
    if (ret == 0) {
3838
        ret = wc_Cshake256_Final(cshake, out, outLen);
3839
    }
3840
    /* wc_Cshake256_Free tolerates a NULL pointer (allocation failure). */
3841
    wc_Cshake256_Free(cshake);
3842
    WC_FREE_VAR_EX(cshake, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3843
3844
    return ret;
3845
}
3846
#endif /* WOLFSSL_CSHAKE256 */
3847
3848
#endif /* (WOLFSSL_KMAC || WOLFSSL_CSHAKE) && WC_SHA3_SW_KECCAK */
3849
3850
#endif /* WOLFSSL_SHA3 */