1 /******************** (C) COPYRIGHT 2012 WildFire Team **************************
10 **********************************************************************************/
11 #include "stm32f10x.h"
12
13 void swap_byte(unsigned char *a, unsigned char *b);
14 /*rc4.c */
15 typedef struct rc4_key
16 {
17 unsigned char state[256];
18 unsigned char x;
19 unsigned char y;
20 } rc4_key;
21
22 void prepare_key(rc4_key *key, unsigned char *key_data_ptr, int key_data_len)
28 {
29 unsigned char index1;
31 unsigned char index2;
32 unsigned char *state;
33 short counter;
34 state = &key->state[0];
35 for(counter = 0; counter < 256; counter++)
36 state[counter] = counter;
37 key->x = 0;
38 key->y = 0;
39 index1 = 0;
40 index2 = 0;
41 for(counter = 0; counter < 256; counter++)
42 {
43 index2 = (key_data_ptr[index1] + state[counter] +index2) % 256;
44 swap_byte(&state[counter], &state[index2]);
45 index1 = (index1 + 1) % key_data_len;
46 }
47 }
48
49 void rc4(rc4_key *key,unsigned char *buffer_ptr, int buffer_len )
50 {
51 unsigned char x;
52 unsigned char y;
53 unsigned char* state;
54 unsigned char xorIndex;
55 short counter;
57 x = key->x;
58 y = key->y;
60 state = &key->state[0];
61 for(counter = 0; counter < buffer_len; counter ++)
62 {
63 x = (x + 1) % 256;
64 y = (state[x] + y) % 256;
65 swap_byte(&state[x], &state[y]);
66
67 xorIndex = (state[x] + state[y]) % 256;
68
69 buffer_ptr[counter] ^= state[xorIndex];
70 }
71 key->x = x;
72 key->y = y;
73 }
74
75 void swap_byte(unsigned char *a, unsigned char *b)
76 {
77 unsigned char swapByte;
78
79 swapByte = *a;
80 *a = *b;
81 *b = swapByte;
82 }
83
84 unsigned char keys[9] = {8,0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef};
85
86
87 int main()
88 {
89 rc4_key s;
90 unsigned char buffer[10] = {0,1,2,3,4,5,6,7,8,9};
91 //数据加密
92 prepare_key(&s, keys, 10); //加密初始化
93 rc4(&s,buffer,10); //将buffer加密,加密成功的数据放在s.state中
94 //数据解密
95 prepare_key(&s, keys, 10); //解密初始化
96 rc4(&s,buffer,10); //将s.state中的数据解密,解密后的数据放在buffer中
97
98 }