arc4.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. /*
  2. * Cryptographic API
  3. *
  4. * ARC4 Cipher Algorithm
  5. *
  6. * Jon Oberheide <jon@oberheide.org>
  7. *
  8. * This program is free software; you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation; either version 2 of the License, or
  11. * (at your option) any later version.
  12. *
  13. */
  14. #include <linux/module.h>
  15. #include <linux/init.h>
  16. #include <linux/crypto.h>
  17. #define ARC4_MIN_KEY_SIZE 1
  18. #define ARC4_MAX_KEY_SIZE 256
  19. #define ARC4_BLOCK_SIZE 1
  20. struct arc4_ctx {
  21. u8 S[256];
  22. u8 x, y;
  23. };
  24. static int arc4_set_key(struct crypto_tfm *tfm, const u8 *in_key,
  25. unsigned int key_len)
  26. {
  27. struct arc4_ctx *ctx = crypto_tfm_ctx(tfm);
  28. int i, j = 0, k = 0;
  29. ctx->x = 1;
  30. ctx->y = 0;
  31. for(i = 0; i < 256; i++)
  32. ctx->S[i] = i;
  33. for(i = 0; i < 256; i++)
  34. {
  35. u8 a = ctx->S[i];
  36. j = (j + in_key[k] + a) & 0xff;
  37. ctx->S[i] = ctx->S[j];
  38. ctx->S[j] = a;
  39. if(++k >= key_len)
  40. k = 0;
  41. }
  42. return 0;
  43. }
  44. static void arc4_crypt(struct crypto_tfm *tfm, u8 *out, const u8 *in)
  45. {
  46. struct arc4_ctx *ctx = crypto_tfm_ctx(tfm);
  47. u8 *const S = ctx->S;
  48. u8 x = ctx->x;
  49. u8 y = ctx->y;
  50. u8 a, b;
  51. a = S[x];
  52. y = (y + a) & 0xff;
  53. b = S[y];
  54. S[x] = b;
  55. S[y] = a;
  56. x = (x + 1) & 0xff;
  57. *out++ = *in ^ S[(a + b) & 0xff];
  58. ctx->x = x;
  59. ctx->y = y;
  60. }
  61. static struct crypto_alg arc4_alg = {
  62. .cra_name = "arc4",
  63. .cra_flags = CRYPTO_ALG_TYPE_CIPHER,
  64. .cra_blocksize = ARC4_BLOCK_SIZE,
  65. .cra_ctxsize = sizeof(struct arc4_ctx),
  66. .cra_module = THIS_MODULE,
  67. .cra_list = LIST_HEAD_INIT(arc4_alg.cra_list),
  68. .cra_u = { .cipher = {
  69. .cia_min_keysize = ARC4_MIN_KEY_SIZE,
  70. .cia_max_keysize = ARC4_MAX_KEY_SIZE,
  71. .cia_setkey = arc4_set_key,
  72. .cia_encrypt = arc4_crypt,
  73. .cia_decrypt = arc4_crypt } }
  74. };
  75. static int __init arc4_init(void)
  76. {
  77. return crypto_register_alg(&arc4_alg);
  78. }
  79. static void __exit arc4_exit(void)
  80. {
  81. crypto_unregister_alg(&arc4_alg);
  82. }
  83. module_init(arc4_init);
  84. module_exit(arc4_exit);
  85. MODULE_LICENSE("GPL");
  86. MODULE_DESCRIPTION("ARC4 Cipher Algorithm");
  87. MODULE_AUTHOR("Jon Oberheide <jon@oberheide.org>");