Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0 OR MIT
0002 /*
0003  * Copyright (C) 2015-2019 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
0004  *
0005  * This is an implementation of the BLAKE2s hash and PRF functions.
0006  *
0007  * Information: https://blake2.net/
0008  *
0009  */
0010 
0011 #include <crypto/internal/blake2s.h>
0012 #include <linux/types.h>
0013 #include <linux/string.h>
0014 #include <linux/kernel.h>
0015 #include <linux/module.h>
0016 #include <linux/init.h>
0017 #include <linux/bug.h>
0018 
0019 static inline void blake2s_set_lastblock(struct blake2s_state *state)
0020 {
0021     state->f[0] = -1;
0022 }
0023 
0024 void blake2s_update(struct blake2s_state *state, const u8 *in, size_t inlen)
0025 {
0026     const size_t fill = BLAKE2S_BLOCK_SIZE - state->buflen;
0027 
0028     if (unlikely(!inlen))
0029         return;
0030     if (inlen > fill) {
0031         memcpy(state->buf + state->buflen, in, fill);
0032         blake2s_compress(state, state->buf, 1, BLAKE2S_BLOCK_SIZE);
0033         state->buflen = 0;
0034         in += fill;
0035         inlen -= fill;
0036     }
0037     if (inlen > BLAKE2S_BLOCK_SIZE) {
0038         const size_t nblocks = DIV_ROUND_UP(inlen, BLAKE2S_BLOCK_SIZE);
0039         blake2s_compress(state, in, nblocks - 1, BLAKE2S_BLOCK_SIZE);
0040         in += BLAKE2S_BLOCK_SIZE * (nblocks - 1);
0041         inlen -= BLAKE2S_BLOCK_SIZE * (nblocks - 1);
0042     }
0043     memcpy(state->buf + state->buflen, in, inlen);
0044     state->buflen += inlen;
0045 }
0046 EXPORT_SYMBOL(blake2s_update);
0047 
0048 void blake2s_final(struct blake2s_state *state, u8 *out)
0049 {
0050     WARN_ON(IS_ENABLED(DEBUG) && !out);
0051     blake2s_set_lastblock(state);
0052     memset(state->buf + state->buflen, 0,
0053            BLAKE2S_BLOCK_SIZE - state->buflen); /* Padding */
0054     blake2s_compress(state, state->buf, 1, state->buflen);
0055     cpu_to_le32_array(state->h, ARRAY_SIZE(state->h));
0056     memcpy(out, state->h, state->outlen);
0057     memzero_explicit(state, sizeof(*state));
0058 }
0059 EXPORT_SYMBOL(blake2s_final);
0060 
0061 static int __init blake2s_mod_init(void)
0062 {
0063     if (!IS_ENABLED(CONFIG_CRYPTO_MANAGER_DISABLE_TESTS) &&
0064         WARN_ON(!blake2s_selftest()))
0065         return -ENODEV;
0066     return 0;
0067 }
0068 
0069 module_init(blake2s_mod_init);
0070 MODULE_LICENSE("GPL v2");
0071 MODULE_DESCRIPTION("BLAKE2s hash function");
0072 MODULE_AUTHOR("Jason A. Donenfeld <Jason@zx2c4.com>");