chacha20.c 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. * ChaCha20 256-bit cipher algorithm, RFC7539
  3. *
  4. * Copyright (C) 2015 Martin Willi
  5. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 2 of the License, or
  9. * (at your option) any later version.
  10. */
  11. #include <linux/kernel.h>
  12. #include <linux/export.h>
  13. #include <linux/bitops.h>
  14. #include <linux/cryptohash.h>
  15. #include <asm/unaligned.h>
  16. #include <crypto/chacha20.h>
  17. static inline u32 rotl32(u32 v, u8 n)
  18. {
  19. return (v << n) | (v >> (sizeof(v) * 8 - n));
  20. }
  21. extern void chacha20_block(u32 *state, void *stream)
  22. {
  23. u32 x[16], *out = stream;
  24. int i;
  25. for (i = 0; i < ARRAY_SIZE(x); i++)
  26. x[i] = state[i];
  27. for (i = 0; i < 20; i += 2) {
  28. x[0] += x[4]; x[12] = rotl32(x[12] ^ x[0], 16);
  29. x[1] += x[5]; x[13] = rotl32(x[13] ^ x[1], 16);
  30. x[2] += x[6]; x[14] = rotl32(x[14] ^ x[2], 16);
  31. x[3] += x[7]; x[15] = rotl32(x[15] ^ x[3], 16);
  32. x[8] += x[12]; x[4] = rotl32(x[4] ^ x[8], 12);
  33. x[9] += x[13]; x[5] = rotl32(x[5] ^ x[9], 12);
  34. x[10] += x[14]; x[6] = rotl32(x[6] ^ x[10], 12);
  35. x[11] += x[15]; x[7] = rotl32(x[7] ^ x[11], 12);
  36. x[0] += x[4]; x[12] = rotl32(x[12] ^ x[0], 8);
  37. x[1] += x[5]; x[13] = rotl32(x[13] ^ x[1], 8);
  38. x[2] += x[6]; x[14] = rotl32(x[14] ^ x[2], 8);
  39. x[3] += x[7]; x[15] = rotl32(x[15] ^ x[3], 8);
  40. x[8] += x[12]; x[4] = rotl32(x[4] ^ x[8], 7);
  41. x[9] += x[13]; x[5] = rotl32(x[5] ^ x[9], 7);
  42. x[10] += x[14]; x[6] = rotl32(x[6] ^ x[10], 7);
  43. x[11] += x[15]; x[7] = rotl32(x[7] ^ x[11], 7);
  44. x[0] += x[5]; x[15] = rotl32(x[15] ^ x[0], 16);
  45. x[1] += x[6]; x[12] = rotl32(x[12] ^ x[1], 16);
  46. x[2] += x[7]; x[13] = rotl32(x[13] ^ x[2], 16);
  47. x[3] += x[4]; x[14] = rotl32(x[14] ^ x[3], 16);
  48. x[10] += x[15]; x[5] = rotl32(x[5] ^ x[10], 12);
  49. x[11] += x[12]; x[6] = rotl32(x[6] ^ x[11], 12);
  50. x[8] += x[13]; x[7] = rotl32(x[7] ^ x[8], 12);
  51. x[9] += x[14]; x[4] = rotl32(x[4] ^ x[9], 12);
  52. x[0] += x[5]; x[15] = rotl32(x[15] ^ x[0], 8);
  53. x[1] += x[6]; x[12] = rotl32(x[12] ^ x[1], 8);
  54. x[2] += x[7]; x[13] = rotl32(x[13] ^ x[2], 8);
  55. x[3] += x[4]; x[14] = rotl32(x[14] ^ x[3], 8);
  56. x[10] += x[15]; x[5] = rotl32(x[5] ^ x[10], 7);
  57. x[11] += x[12]; x[6] = rotl32(x[6] ^ x[11], 7);
  58. x[8] += x[13]; x[7] = rotl32(x[7] ^ x[8], 7);
  59. x[9] += x[14]; x[4] = rotl32(x[4] ^ x[9], 7);
  60. }
  61. for (i = 0; i < ARRAY_SIZE(x); i++)
  62. out[i] = cpu_to_le32(x[i] + state[i]);
  63. state[12]++;
  64. }
  65. EXPORT_SYMBOL(chacha20_block);