add some comments
[tridge/junkcode.git] / rc4.c
1 /*rc4.c */
2 #include "rc4.h"
3 static void swap_byte(unsigned char *a, unsigned char *b);
4 void prepare_key(unsigned char *key_data_ptr, int key_data_len,
5 rc4_key *key)
6 {
7      unsigned char swapByte;
8      unsigned char index1;
9      unsigned char index2;
10      unsigned char* state;
11      short counter;     
12      
13      state = &key->state[0];         
14      for(counter = 0; counter < 256; counter++)              
15      state[counter] = counter;               
16      key->x = 0;     
17      key->y = 0;     
18      index1 = 0;     
19      index2 = 0;             
20      for(counter = 0; counter < 256; counter++)      
21      {               
22           index2 = (key_data_ptr[index1] + state[counter] +
23 index2) % 256;                
24           swap_byte(&state[counter], &state[index2]);            
25
26           index1 = (index1 + 1) % key_data_len;  
27      }       
28  }
29  
30  void rc4(unsigned char *buffer_ptr, int buffer_len, rc4_key
31 *key)
32  { 
33      unsigned char x;
34      unsigned char y;
35      unsigned char* state;
36      unsigned char xorIndex;
37      short counter;              
38      
39      x = key->x;     
40      y = key->y;     
41      
42      state = &key->state[0];         
43      for(counter = 0; counter < buffer_len; counter ++)      
44      {               
45           x = (x + 1) % 256;                      
46           y = (state[x] + y) % 256;               
47           swap_byte(&state[x], &state[y]);                        
48                
49           xorIndex = (state[x] + state[y]) % 256;                 
50                
51           buffer_ptr[counter] ^= state[xorIndex];         
52       }               
53       key->x = x;     
54       key->y = y;
55  }
56  
57  static void swap_byte(unsigned char *a, unsigned char *b)
58  {
59      unsigned char swapByte; 
60      
61      swapByte = *a; 
62      *a = *b;      
63      *b = swapByte;
64  }