ARC4.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*
  2. * arc4.c : Implementation for the Alleged-RC4 stream cipher
  3. *
  4. * Part of the Python Cryptography Toolkit
  5. *
  6. * Originally written by: A.M. Kuchling
  7. *
  8. * ===================================================================
  9. * The contents of this file are dedicated to the public domain. To
  10. * the extent that dedication to the public domain is not available,
  11. * everyone is granted a worldwide, perpetual, royalty-free,
  12. * non-exclusive license to exercise all rights associated with the
  13. * contents of this file for any purpose whatsoever.
  14. * No rights are reserved.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  17. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  18. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  19. * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  20. * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  21. * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  22. * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  23. * SOFTWARE.
  24. * ===================================================================
  25. *
  26. */
  27. #define MODULE_NAME _ARC4
  28. #define BLOCK_SIZE 1
  29. #define KEY_SIZE 0
  30. typedef struct
  31. {
  32. unsigned char state[256];
  33. unsigned char x,y;
  34. } stream_state;
  35. /* Encryption and decryption are symmetric */
  36. #define stream_decrypt stream_encrypt
  37. static void stream_encrypt(stream_state *self, unsigned char *block,
  38. int len)
  39. {
  40. register int i, x=self->x, y=self->y;
  41. for (i=0; i<len; i++)
  42. {
  43. x = (x + 1) % 256;
  44. y = (y + self->state[x]) % 256;
  45. {
  46. register int t; /* Exchange state[x] and state[y] */
  47. t = self->state[x];
  48. self->state[x] = self->state[y];
  49. self->state[y] = t;
  50. }
  51. {
  52. register int xorIndex; /* XOR the data with the stream data */
  53. xorIndex=(self->state[x]+self->state[y]) % 256;
  54. block[i] ^= self->state[xorIndex];
  55. }
  56. }
  57. self->x=x;
  58. self->y=y;
  59. }
  60. static void stream_init(stream_state *self, unsigned char *key, int keylen)
  61. {
  62. register int i, index1, index2;
  63. for(i=0; i<256; i++) self->state[i]=i;
  64. self->x=0; self->y=0;
  65. index1=0; index2=0;
  66. for(i=0; i<256; i++)
  67. {
  68. register int t;
  69. index2 = ( key[index1] + self->state[i] + index2) % 256;
  70. t = self->state[i];
  71. self->state[i] = self->state[index2];
  72. self->state[index2] = t;
  73. index1 = (index1 + 1) % keylen;
  74. }
  75. }
  76. #include "stream_template.c"