xref: /freebsd/crypto/libecc/src/hash/shake256.c (revision f0865ec9906d5a18fa2a3b61381f22ce16e606ad)
1 /*
2  *  Copyright (C) 2021 - This file is part of libecc project
3  *
4  *  Authors:
5  *      Ryad BENADJILA <ryadbenadjila@gmail.com>
6  *      Arnaud EBALARD <arnaud.ebalard@ssi.gouv.fr>
7  *
8  *  This software is licensed under a dual BSD and GPL v2 license.
9  *  See LICENSE file at the root folder of the project.
10  */
11 #include <libecc/lib_ecc_config.h>
12 #ifdef WITH_HASH_SHAKE256
13 
14 #include <libecc/hash/shake256.h>
15 
shake256_init(shake256_context * ctx)16 int shake256_init(shake256_context *ctx)
17 {
18 	int ret;
19 
20 	ret = _shake_init(ctx, SHAKE256_DIGEST_SIZE, SHAKE256_BLOCK_SIZE); EG(ret, err);
21 
22 	/* Tell that we are initialized */
23 	ctx->magic = SHAKE256_HASH_MAGIC;
24 
25 err:
26 	return ret;
27 }
28 
shake256_update(shake256_context * ctx,const u8 * input,u32 ilen)29 int shake256_update(shake256_context *ctx, const u8 *input, u32 ilen)
30 {
31 	int ret;
32 
33 	SHAKE256_HASH_CHECK_INITIALIZED(ctx, ret, err);
34 
35 	ret = _shake_update((shake_context *)ctx, input, ilen);
36 
37 err:
38 	return ret;
39 }
40 
shake256_final(shake256_context * ctx,u8 output[SHAKE256_DIGEST_SIZE])41 int shake256_final(shake256_context *ctx, u8 output[SHAKE256_DIGEST_SIZE])
42 {
43 	int ret;
44 
45 	SHAKE256_HASH_CHECK_INITIALIZED(ctx, ret, err);
46 
47 	ret = _shake_finalize((shake_context *)ctx, output);
48 
49 	/* Tell that we are uninitialized */
50 	ctx->magic = WORD(0);
51 
52 err:
53 	return ret;
54 }
55 
shake256_scattered(const u8 ** inputs,const u32 * ilens,u8 output[SHAKE256_DIGEST_SIZE])56 int shake256_scattered(const u8 **inputs, const u32 *ilens,
57 			u8 output[SHAKE256_DIGEST_SIZE])
58 {
59 	shake256_context ctx;
60 	int pos = 0, ret;
61 
62 	MUST_HAVE((inputs != NULL) && (ilens != NULL) && (output != NULL), ret, err);
63 
64 	ret = shake256_init(&ctx); EG(ret, err);
65 
66 	while (inputs[pos] != NULL) {
67 		ret = shake256_update(&ctx, inputs[pos], ilens[pos]); EG(ret, err);
68 		pos += 1;
69 	}
70 
71 	ret = shake256_final(&ctx, output);
72 
73 err:
74 	return ret;
75 }
76 
shake256(const u8 * input,u32 ilen,u8 output[SHAKE256_DIGEST_SIZE])77 int shake256(const u8 *input, u32 ilen, u8 output[SHAKE256_DIGEST_SIZE])
78 {
79 	int ret;
80 	shake256_context ctx;
81 
82 	ret = shake256_init(&ctx); EG(ret, err);
83 	ret = shake256_update(&ctx, input, ilen); EG(ret, err);
84 	ret = shake256_final(&ctx, output);
85 
86 err:
87 	return ret;
88 }
89 
90 #else /* WITH_HASH_SHAKE256 */
91 
92 /*
93  * Dummy definition to avoid the empty translation unit ISO C warning
94  */
95 typedef int dummy;
96 #endif /* WITH_HASH_SHAKE256 */
97