aboutsummaryrefslogtreecommitdiff
path: root/src/libsec/port/rc4.c
blob: beafa4868dc1e00b032d2459ee8bd948f5dd3b8d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include "os.h"
#include <libsec.h>

void
setupRC4state(RC4state *key, uchar *start, int n)
{
	int t;
	int index2;
	uchar *state;
	uchar *p, *e, *sp, *se;

	state = key->state;
	se = &state[256];
	for(sp = state; sp < se; sp++)
		*sp = sp - state;

	key->x = 0;
	key->y = 0;
	index2 = 0;
	e = start + n;
	p = start;
	for(sp = state; sp < se; sp++)
	{
		t = *sp;
		index2 = (*p + t + index2) & 255;
		*sp = state[index2];
		state[index2] = t;
		if(++p >= e)
			p = start;
	}
}

void
rc4(RC4state *key, uchar *p, int len)
{
	int tx, ty;
	int x, y;
	uchar *state;
	uchar *e;

	x = key->x;
	y = key->y;
	state = &key->state[0];
	for(e = p + len; p < e; p++)
	{
		x = (x+1)&255;
		tx = state[x];
		y = (y+tx)&255;
		ty = state[y];
		state[x] = ty;
		state[y] = tx;
		*p ^= state[(tx+ty)&255];
	}
	key->x = x;
	key->y = y;
}

void
rc4skip(RC4state *key, int len)
{
	int tx, ty;
	int x, y;
	uchar *state;
	int i;

	x = key->x;
	y = key->y;
	state = &key->state[0];
	for(i=0; i<len; i++)
	{
		x = (x+1)&255;
		tx = state[x];
		y = (y+tx)&255;
		ty = state[y];
		state[x] = ty;
		state[y] = tx;
	}
	key->x = x;
	key->y = y;
}

void
rc4back(RC4state *key, int len)
{
	int tx, ty;
	int x, y;
	uchar *state;
	int i;

	x = key->x;
	y = key->y;
	state = &key->state[0];
	for(i=0; i<len; i++)
	{
		ty = state[x];
		tx = state[y];
		state[y] = ty;
		state[x] = tx;
		y = (y-tx)&255;
		x = (x-1)&255;
	}
	key->x = x;
	key->y = y;
}