arcfour.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /* arcfour.c */
  2. /*
  3. This file is part of the ARM-Crypto-Lib.
  4. Copyright (C) 2006-2010 Daniel Otte (daniel.otte@rub.de)
  5. This program is free software: you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation, either version 3 of the License, or
  8. (at your option) any later version.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with this program. If not, see <http://www.gnu.org/licenses/>.
  15. */
  16. /*
  17. * File: arcfour.c
  18. * Author: Daniel Otte
  19. * email: daniel.otte@rub.de
  20. * Date: 2006-06-07
  21. * License: GPLv3 or later
  22. * Description: Implementation of the ARCFOUR (RC4 compatible) stream cipher algorithm.
  23. *
  24. */
  25. #include <stdint.h>
  26. #include <crypto/arcfour.h>
  27. /*
  28. * length is length of key in bits!
  29. */
  30. void arcfour_init(const void *key, uint16_t length_b, arcfour_ctx_t *ctx){
  31. uint8_t t;
  32. uint8_t x=0,y=0;
  33. length_b /= 8;
  34. const uint8_t *kptr, *limit;
  35. limit = (uint8_t*)key + length_b;
  36. kptr = key;
  37. do{
  38. ctx->s[x]=x;
  39. }while(++x);
  40. do{
  41. y += ctx->s[x] + *kptr++;
  42. if(kptr==limit){
  43. kptr=key;
  44. }
  45. /* ctx->s[y] <--> ctx->s[x] */
  46. t = ctx->s[y];
  47. ctx->s[y] = ctx->s[x];
  48. ctx->s[x] = t;
  49. }while(++x);
  50. ctx->i = ctx->j = 0;
  51. }
  52. uint8_t arcfour_gen(arcfour_ctx_t *ctx){
  53. uint8_t t;
  54. ctx->i++;
  55. ctx->j += ctx->s[ctx->i];
  56. /* ctx->s[i] <--> ctx->s[j] */
  57. t = ctx->s[ctx->j];
  58. ctx->s[ctx->j] = ctx->s[ctx->i];
  59. ctx->s[ctx->i] = t;
  60. return ctx->s[(ctx->s[ctx->j] + ctx->s[ctx->i]) & 0xff];
  61. }