arc4.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /* arc4.c
  2. *
  3. * Copyright (C) 2006-2011 Sawtooth Consulting Ltd.
  4. *
  5. * This file is part of CyaSSL.
  6. *
  7. * CyaSSL is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * CyaSSL is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
  20. */
  21. #include "arc4.h"
  22. void Arc4SetKey(Arc4* arc4, const byte* key, word32 length)
  23. {
  24. word32 i;
  25. word32 keyIndex = 0, stateIndex = 0;
  26. arc4->x = 1;
  27. arc4->y = 0;
  28. for (i = 0; i < ARC4_STATE_SIZE; i++)
  29. arc4->state[i] = i;
  30. for (i = 0; i < ARC4_STATE_SIZE; i++) {
  31. word32 a = arc4->state[i];
  32. stateIndex += key[keyIndex] + a;
  33. stateIndex &= 0xFF;
  34. arc4->state[i] = arc4->state[stateIndex];
  35. arc4->state[stateIndex] = a;
  36. if (++keyIndex >= length)
  37. keyIndex = 0;
  38. }
  39. }
  40. static INLINE word32 MakeByte(word32* x, word32* y, byte* s)
  41. {
  42. word32 a = s[*x], b;
  43. *y = (*y+a) & 0xff;
  44. b = s[*y];
  45. s[*x] = b;
  46. s[*y] = a;
  47. *x = (*x+1) & 0xff;
  48. return s[(a+b) & 0xff];
  49. }
  50. void Arc4Process(Arc4* arc4, byte* out, const byte* in, word32 length)
  51. {
  52. word32 x = arc4->x;
  53. word32 y = arc4->y;
  54. while(length--)
  55. *out++ = *in++ ^ MakeByte(&x, &y, arc4->state);
  56. arc4->x = x;
  57. arc4->y = y;
  58. }