source: titan/titan/rc4.h @ 40904

Last change on this file since 40904 was 17470, checked in by nit, 12 years ago

[titan] fixes

File size: 975 bytes
Line 
1#ifndef RC4_H
2#define RC4_H
3
4struct rc4ctx
5{
6        unsigned char S[256];
7        unsigned char i;
8        unsigned char j;
9};
10
11#define SWAPRC4(a, b) { unsigned char temp; temp = (a); (a) = (b); (b) = temp; }
12
13void rc4init(struct rc4ctx *ctx, char *key, size_t keylen)
14{
15        int i;
16        unsigned char j = 0;
17
18        if(key == NULL) return;
19
20        for(i = 0; i < sizeof(ctx->S); i++)
21                ctx->S[i] = i;
22   
23        for(i = 0; i < sizeof(ctx->S); i++)
24        {
25                j += (ctx->S[i] + key[i % keylen]);
26                SWAPRC4(ctx->S[i], ctx->S[j]);
27        }
28}
29
30void rc4crypt(struct rc4ctx *ctx, char *data, size_t len)
31{
32        unsigned int i;
33
34        if(data == NULL) return;
35
36        ctx->i = 0;
37        ctx->j = 0;
38
39        for(i = 0; i < len; i++)
40        {
41                unsigned char s;
42
43                ctx->i++;
44                ctx->j += ctx->S[ctx->i];
45
46                SWAPRC4(ctx->S[ctx->i], ctx->S[ctx->j]);
47
48                s = ctx->S[ctx->i] + ctx->S[ctx->j];
49                data[i] = data[i] ^ ctx->S[s];
50        }
51}
52
53void rc4(char *data, size_t dlen, char *key, size_t klen)
54{
55        struct rc4ctx ctx;
56
57        rc4init(&ctx, key, klen);
58        rc4crypt(&ctx, data, dlen);
59}
60
61#endif
Note: See TracBrowser for help on using the repository browser.