GNU Linux-libre 4.9.337-gnu1
[releases.git] / lib / crypto / blake2s.c
1 // SPDX-License-Identifier: GPL-2.0 OR MIT
2 /*
3  * Copyright (C) 2015-2019 Jason A. Donenfeld <Jason@zx2c4.com>. 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/types.h>
13 #include <linux/string.h>
14 #include <linux/kernel.h>
15 #include <linux/module.h>
16 #include <linux/init.h>
17 #include <linux/bug.h>
18 #include <asm/unaligned.h>
19
20 bool blake2s_selftest(void);
21
22 void blake2s_update(struct blake2s_state *state, const u8 *in, size_t inlen)
23 {
24         const size_t fill = BLAKE2S_BLOCK_SIZE - state->buflen;
25
26         if (unlikely(!inlen))
27                 return;
28         if (inlen > fill) {
29                 memcpy(state->buf + state->buflen, in, fill);
30                 blake2s_compress_generic(state, state->buf, 1,
31                                          BLAKE2S_BLOCK_SIZE);
32                 state->buflen = 0;
33                 in += fill;
34                 inlen -= fill;
35         }
36         if (inlen > BLAKE2S_BLOCK_SIZE) {
37                 const size_t nblocks = DIV_ROUND_UP(inlen, BLAKE2S_BLOCK_SIZE);
38                 /* Hash one less (full) block than strictly possible */
39                 blake2s_compress_generic(state, in, nblocks - 1,
40                                          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_generic(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 mod_init(void)
63 {
64         if (!IS_ENABLED(CONFIG_CRYPTO_MANAGER_DISABLE_TESTS) &&
65             WARN_ON(!blake2s_selftest()))
66                 return -ENODEV;
67         return 0;
68 }
69
70 static void __exit mod_exit(void)
71 {
72 }
73
74 module_init(mod_init);
75 module_exit(mod_exit);
76 MODULE_LICENSE("GPL v2");
77 MODULE_DESCRIPTION("BLAKE2s hash function");
78 MODULE_AUTHOR("Jason A. Donenfeld <Jason@zx2c4.com>");