arc4.c 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // SPDX-License-Identifier: GPL-2.0-or-later
  2. /*
  3. * Cryptographic API
  4. *
  5. * ARC4 Cipher Algorithm
  6. *
  7. * Jon Oberheide <jon@oberheide.org>
  8. */
  9. #include <crypto/arc4.h>
  10. #include <linux/module.h>
  11. int arc4_setkey(struct arc4_ctx *ctx, const u8 *in_key, unsigned int key_len)
  12. {
  13. int i, j = 0, k = 0;
  14. ctx->x = 1;
  15. ctx->y = 0;
  16. for (i = 0; i < 256; i++)
  17. ctx->S[i] = i;
  18. for (i = 0; i < 256; i++) {
  19. u32 a = ctx->S[i];
  20. j = (j + in_key[k] + a) & 0xff;
  21. ctx->S[i] = ctx->S[j];
  22. ctx->S[j] = a;
  23. if (++k >= key_len)
  24. k = 0;
  25. }
  26. return 0;
  27. }
  28. EXPORT_SYMBOL(arc4_setkey);
  29. void arc4_crypt(struct arc4_ctx *ctx, u8 *out, const u8 *in, unsigned int len)
  30. {
  31. u32 *const S = ctx->S;
  32. u32 x, y, a, b;
  33. u32 ty, ta, tb;
  34. if (len == 0)
  35. return;
  36. x = ctx->x;
  37. y = ctx->y;
  38. a = S[x];
  39. y = (y + a) & 0xff;
  40. b = S[y];
  41. do {
  42. S[y] = a;
  43. a = (a + b) & 0xff;
  44. S[x] = b;
  45. x = (x + 1) & 0xff;
  46. ta = S[x];
  47. ty = (y + ta) & 0xff;
  48. tb = S[ty];
  49. *out++ = *in++ ^ S[a];
  50. if (--len == 0)
  51. break;
  52. y = ty;
  53. a = ta;
  54. b = tb;
  55. } while (true);
  56. ctx->x = x;
  57. ctx->y = y;
  58. }
  59. EXPORT_SYMBOL(arc4_crypt);
  60. MODULE_LICENSE("GPL");