blake2s.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. #include <crypto/internal/blake2s.h>
  11. #include <linux/types.h>
  12. #include <linux/string.h>
  13. #include <linux/kernel.h>
  14. #include <linux/module.h>
  15. #include <linux/init.h>
  16. #include <linux/bug.h>
  17. static inline void blake2s_set_lastblock(struct blake2s_state *state)
  18. {
  19. state->f[0] = -1;
  20. }
  21. void blake2s_update(struct blake2s_state *state, const u8 *in, size_t inlen)
  22. {
  23. const size_t fill = BLAKE2S_BLOCK_SIZE - state->buflen;
  24. if (unlikely(!inlen))
  25. return;
  26. if (inlen > fill) {
  27. memcpy(state->buf + state->buflen, in, fill);
  28. blake2s_compress(state, state->buf, 1, BLAKE2S_BLOCK_SIZE);
  29. state->buflen = 0;
  30. in += fill;
  31. inlen -= fill;
  32. }
  33. if (inlen > BLAKE2S_BLOCK_SIZE) {
  34. const size_t nblocks = DIV_ROUND_UP(inlen, BLAKE2S_BLOCK_SIZE);
  35. blake2s_compress(state, in, nblocks - 1, BLAKE2S_BLOCK_SIZE);
  36. in += BLAKE2S_BLOCK_SIZE * (nblocks - 1);
  37. inlen -= BLAKE2S_BLOCK_SIZE * (nblocks - 1);
  38. }
  39. memcpy(state->buf + state->buflen, in, inlen);
  40. state->buflen += inlen;
  41. }
  42. EXPORT_SYMBOL(blake2s_update);
  43. void blake2s_final(struct blake2s_state *state, u8 *out)
  44. {
  45. WARN_ON(IS_ENABLED(DEBUG) && !out);
  46. blake2s_set_lastblock(state);
  47. memset(state->buf + state->buflen, 0,
  48. BLAKE2S_BLOCK_SIZE - state->buflen); /* Padding */
  49. blake2s_compress(state, state->buf, 1, state->buflen);
  50. cpu_to_le32_array(state->h, ARRAY_SIZE(state->h));
  51. memcpy(out, state->h, state->outlen);
  52. memzero_explicit(state, sizeof(*state));
  53. }
  54. EXPORT_SYMBOL(blake2s_final);
  55. static int __init blake2s_mod_init(void)
  56. {
  57. if (!IS_ENABLED(CONFIG_CRYPTO_MANAGER_DISABLE_TESTS) &&
  58. WARN_ON(!blake2s_selftest()))
  59. return -ENODEV;
  60. return 0;
  61. }
  62. module_init(blake2s_mod_init);
  63. MODULE_LICENSE("GPL v2");
  64. MODULE_DESCRIPTION("BLAKE2s hash function");
  65. MODULE_AUTHOR("Jason A. Donenfeld <[email protected]>");