Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
torvalds
GitHub Repository: torvalds/linux
Path: blob/master/lib/crypto/blake2s.c
26282 views
1
// SPDX-License-Identifier: GPL-2.0 OR MIT
2
/*
3
* Copyright (C) 2015-2019 Jason A. Donenfeld <[email protected]>. All Rights Reserved.
4
*
5
* This is an implementation of the BLAKE2s hash and PRF functions.
6
*
7
* Information: https://blake2.net/
8
*
9
*/
10
11
#include <crypto/internal/blake2s.h>
12
#include <linux/bug.h>
13
#include <linux/export.h>
14
#include <linux/init.h>
15
#include <linux/kernel.h>
16
#include <linux/module.h>
17
#include <linux/string.h>
18
#include <linux/types.h>
19
20
static inline void blake2s_set_lastblock(struct blake2s_state *state)
21
{
22
state->f[0] = -1;
23
}
24
25
void blake2s_update(struct blake2s_state *state, const u8 *in, size_t inlen)
26
{
27
const size_t fill = BLAKE2S_BLOCK_SIZE - state->buflen;
28
29
if (unlikely(!inlen))
30
return;
31
if (inlen > fill) {
32
memcpy(state->buf + state->buflen, in, fill);
33
blake2s_compress(state, state->buf, 1, BLAKE2S_BLOCK_SIZE);
34
state->buflen = 0;
35
in += fill;
36
inlen -= fill;
37
}
38
if (inlen > BLAKE2S_BLOCK_SIZE) {
39
const size_t nblocks = DIV_ROUND_UP(inlen, BLAKE2S_BLOCK_SIZE);
40
blake2s_compress(state, in, nblocks - 1, BLAKE2S_BLOCK_SIZE);
41
in += BLAKE2S_BLOCK_SIZE * (nblocks - 1);
42
inlen -= BLAKE2S_BLOCK_SIZE * (nblocks - 1);
43
}
44
memcpy(state->buf + state->buflen, in, inlen);
45
state->buflen += inlen;
46
}
47
EXPORT_SYMBOL(blake2s_update);
48
49
void blake2s_final(struct blake2s_state *state, u8 *out)
50
{
51
WARN_ON(IS_ENABLED(DEBUG) && !out);
52
blake2s_set_lastblock(state);
53
memset(state->buf + state->buflen, 0,
54
BLAKE2S_BLOCK_SIZE - state->buflen); /* Padding */
55
blake2s_compress(state, state->buf, 1, state->buflen);
56
cpu_to_le32_array(state->h, ARRAY_SIZE(state->h));
57
memcpy(out, state->h, state->outlen);
58
memzero_explicit(state, sizeof(*state));
59
}
60
EXPORT_SYMBOL(blake2s_final);
61
62
static int __init blake2s_mod_init(void)
63
{
64
if (IS_ENABLED(CONFIG_CRYPTO_SELFTESTS) &&
65
WARN_ON(!blake2s_selftest()))
66
return -ENODEV;
67
return 0;
68
}
69
70
module_init(blake2s_mod_init);
71
MODULE_DESCRIPTION("BLAKE2s hash function");
72
MODULE_AUTHOR("Jason A. Donenfeld <[email protected]>");
73
74