crypt_arc4.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /* This code illustrates a sample implementation
  2. * of the Arcfour algorithm
  3. * Copyright (c) April 29, 1997 Kalle Kaukonen.
  4. * All Rights Reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or
  7. * without modification, are permitted provided that this copyright
  8. * notice and disclaimer are retained.
  9. *
  10. * THIS SOFTWARE IS PROVIDED BY KALLE KAUKONEN AND CONTRIBUTORS ``AS
  11. * IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  12. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  13. * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KALLE
  14. * KAUKONEN OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  15. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  16. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  17. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  18. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  19. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  20. * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  21. * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  22. */
  23. #include "fitz-internal.h"
  24. void
  25. fz_arc4_init(fz_arc4 *arc4, const unsigned char *key, unsigned keylen)
  26. {
  27. unsigned int t, u;
  28. unsigned int keyindex;
  29. unsigned int stateindex;
  30. unsigned char *state;
  31. unsigned int counter;
  32. state = arc4->state;
  33. arc4->x = 0;
  34. arc4->y = 0;
  35. for (counter = 0; counter < 256; counter++)
  36. {
  37. state[counter] = counter;
  38. }
  39. keyindex = 0;
  40. stateindex = 0;
  41. for (counter = 0; counter < 256; counter++)
  42. {
  43. t = state[counter];
  44. stateindex = (stateindex + key[keyindex] + t) & 0xff;
  45. u = state[stateindex];
  46. state[stateindex] = t;
  47. state[counter] = u;
  48. if (++keyindex >= keylen)
  49. {
  50. keyindex = 0;
  51. }
  52. }
  53. }
  54. static unsigned char
  55. fz_arc4_next(fz_arc4 *arc4)
  56. {
  57. unsigned int x;
  58. unsigned int y;
  59. unsigned int sx, sy;
  60. unsigned char *state;
  61. state = arc4->state;
  62. x = (arc4->x + 1) & 0xff;
  63. sx = state[x];
  64. y = (sx + arc4->y) & 0xff;
  65. sy = state[y];
  66. arc4->x = x;
  67. arc4->y = y;
  68. state[y] = sx;
  69. state[x] = sy;
  70. return state[(sx + sy) & 0xff];
  71. }
  72. void
  73. fz_arc4_encrypt(fz_arc4 *arc4, unsigned char *dest, const unsigned char *src, unsigned len)
  74. {
  75. unsigned int i;
  76. for (i = 0; i < len; i++)
  77. {
  78. unsigned char x;
  79. x = fz_arc4_next(arc4);
  80. dest[i] = src[i] ^ x;
  81. }
  82. }