rc4.c (1415B)
1 #include "os.h" 2 #include "libsec.h" 3 4 void 5 setupRC4state(RC4state *key, uchar *start, int n) 6 { 7 int t; 8 int index2; 9 uchar *state; 10 uchar *p, *e, *sp, *se; 11 12 state = key->state; 13 se = &state[256]; 14 for(sp = state; sp < se; sp++) 15 *sp = sp - state; 16 17 key->x = 0; 18 key->y = 0; 19 index2 = 0; 20 e = start + n; 21 p = start; 22 for(sp = state; sp < se; sp++) 23 { 24 t = *sp; 25 index2 = (*p + t + index2) & 255; 26 *sp = state[index2]; 27 state[index2] = t; 28 if(++p >= e) 29 p = start; 30 } 31 } 32 33 void 34 rc4(RC4state *key, uchar *p, int len) 35 { 36 int tx, ty; 37 int x, y; 38 uchar *state; 39 uchar *e; 40 41 x = key->x; 42 y = key->y; 43 state = &key->state[0]; 44 for(e = p + len; p < e; p++) 45 { 46 x = (x+1)&255; 47 tx = state[x]; 48 y = (y+tx)&255; 49 ty = state[y]; 50 state[x] = ty; 51 state[y] = tx; 52 *p ^= state[(tx+ty)&255]; 53 } 54 key->x = x; 55 key->y = y; 56 } 57 58 void 59 rc4skip(RC4state *key, int len) 60 { 61 int tx, ty; 62 int x, y; 63 uchar *state; 64 int i; 65 66 x = key->x; 67 y = key->y; 68 state = &key->state[0]; 69 for(i=0; i<len; i++) 70 { 71 x = (x+1)&255; 72 tx = state[x]; 73 y = (y+tx)&255; 74 ty = state[y]; 75 state[x] = ty; 76 state[y] = tx; 77 } 78 key->x = x; 79 key->y = y; 80 } 81 82 void 83 rc4back(RC4state *key, int len) 84 { 85 int tx, ty; 86 int x, y; 87 uchar *state; 88 int i; 89 90 x = key->x; 91 y = key->y; 92 state = &key->state[0]; 93 for(i=0; i<len; i++) 94 { 95 ty = state[x]; 96 tx = state[y]; 97 state[y] = ty; 98 state[x] = tx; 99 y = (y-tx)&255; 100 x = (x-1)&255; 101 } 102 key->x = x; 103 key->y = y; 104 }