This repository has been archived by the owner on Jan 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 86
/
shake.c
103 lines (85 loc) · 2.93 KB
/
shake.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/*
* Copyright (C) 2021 - This file is part of libecc project
*
* Authors:
* Ryad BENADJILA <ryadbenadjila@gmail.com>
* Arnaud EBALARD <arnaud.ebalard@ssi.gouv.fr>
*
* This software is licensed under a dual BSD and GPL v2 license.
* See LICENSE file at the root folder of the project.
*/
#include "../utils/utils.h"
#include "shake.h"
/* Init function depending on the digest size */
int _shake_init(shake_context *ctx, u8 digest_size, u8 block_size)
{
int ret;
MUST_HAVE((ctx != NULL), ret, err);
/* Zeroize the internal state */
ret = local_memset(ctx->shake_state, 0, sizeof(ctx->shake_state)); EG(ret, err);
ctx->shake_idx = 0;
ctx->shake_digest_size = digest_size;
ctx->shake_block_size = block_size;
/* Detect endianness */
ctx->shake_endian = arch_is_big_endian() ? SHAKE_BIG : SHAKE_LITTLE;
err:
return ret;
}
/* Update hash function */
int _shake_update(shake_context *ctx, const u8 *input, u32 ilen)
{
u32 i;
u8 *state;
int ret;
MUST_HAVE((ctx != NULL) && ((input != NULL) || (ilen == 0)), ret, err);
state = (u8*)(ctx->shake_state);
for(i = 0; i < ilen; i++){
/* Compute the index depending on the endianness */
u64 idx = (ctx->shake_endian == SHAKE_LITTLE) ? ctx->shake_idx : SWAP64_Idx(ctx->shake_idx);
ctx->shake_idx++;
/* Update the state, and adapt endianness order */
state[idx] ^= input[i];
if(ctx->shake_idx == ctx->shake_block_size){
KECCAKF(ctx->shake_state);
ctx->shake_idx = 0;
}
}
ret = 0;
err:
return ret;
}
/* Finalize hash function */
int _shake_finalize(shake_context *ctx, u8 *output)
{
unsigned int i;
u8 *state;
int ret;
MUST_HAVE((ctx != NULL) && (output != NULL), ret, err);
MUST_HAVE((ctx->shake_digest_size <= sizeof(ctx->shake_state)), ret, err);
state = (u8*)(ctx->shake_state);
/* Proceed with the padding of the last block */
/* Compute the index depending on the endianness */
if(ctx->shake_endian == SHAKE_LITTLE){
/* Little endian case */
state[ctx->shake_idx] ^= 0x1f;
state[ctx->shake_block_size - 1] ^= 0x80;
}
else{
/* Big endian case */
state[SWAP64_Idx(ctx->shake_idx)] ^= 0x1f;
state[SWAP64_Idx(ctx->shake_block_size - 1)] ^= 0x80;
}
/* Produce the output.
* NOTE: we should have a fixed version of SHAKE producing an output size
* with size less than the state size.
*/
KECCAKF(ctx->shake_state);
for(i = 0; i < ctx->shake_digest_size; i++){
output[i] = (ctx->shake_endian == SHAKE_LITTLE) ? state[i] : state[SWAP64_Idx(i)];
}
/* Uninit our context magic */
ctx->magic = WORD(0);
ret = 0;
err:
return ret;
}