-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrc4.c
86 lines (66 loc) · 1.95 KB
/
rc4.c
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
#include "rc4.h"
void rc4_init(rc4_state_t *state, const unsigned char *key, unsigned int keylen)
{
unsigned char j;
unsigned char tmp;
int i;
for (i = 0; i < 256; i++)
state->buffer[i] = i;
state->x = 0;
state->y = 0;
if (keylen > 0) { /* 0 modulo 0 is undefined anyway. */
for (i = j = 0; i < 256; i++) {
j += state->buffer[i] + key[i%keylen];
tmp = state->buffer[i];
state->buffer[i] = state->buffer[j];
state->buffer[j] = tmp;
}
}
}
void rc4_encrypt(rc4_state_t *state, const unsigned char *in, unsigned char *out, unsigned long len)
{
unsigned char x, y;
unsigned char tmp;
unsigned char k; /* Keystream. */
unsigned long i;
x = state->x;
y = state->y;
for (i = 0; i < len; i++) {
x++;
y += state->buffer[x];
tmp = state->buffer[x];
state->buffer[x] = state->buffer[y];
state->buffer[y] = tmp;
k = state->buffer[(state->buffer[x] + state->buffer[y]) & 0xff];
out[i] = in[i] ^ k;
}
state->x = x;
state->y = y;
}
void rc4_encrypt_skip(rc4_state_t *state, const unsigned char *in, unsigned char *out, unsigned long len, unsigned long skip)
{
unsigned char x, y;
unsigned char tmp;
unsigned char k; /* Keystream. */
unsigned long i;
x = state->x;
y = state->y;
for (i = 0; i < skip; i++) {
x++;
y += state->buffer[x];
tmp = state->buffer[x];
state->buffer[x] = state->buffer[y];
state->buffer[y] = tmp;
}
for (i = 0; i < len; i++) {
x++;
y += state->buffer[x];
tmp = state->buffer[x];
state->buffer[x] = state->buffer[y];
state->buffer[y] = tmp;
k= state->buffer[(state->buffer[x] + state->buffer[y]) & 0xff];
out[i] = in[i] ^ k;
}
state->x = x;
state->y = y;
}