• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * RC4 stream cipher
3  * Copyright (c) 2002-2005, Jouni Malinen <j@w1.fi>
4  *
5  * This software may be distributed under the terms of the BSD license.
6  * See README for more details.
7  */
8 
9 #include "includes.h"
10 
11 #include "common.h"
12 #include "crypto.h"
13 
14 #define S_SWAP(a,b) do { u8 t = S[a]; S[a] = S[b]; S[b] = t; } while(0)
15 
rc4_skip(const u8 * key,size_t keylen,size_t skip,u8 * data,size_t data_len)16 int rc4_skip(const u8 *key, size_t keylen, size_t skip,
17 	     u8 *data, size_t data_len)
18 {
19 	u32 i, j, k;
20 	u8 S[256], *pos;
21 	size_t kpos;
22 
23 	/* Setup RC4 state */
24 	for (i = 0; i < 256; i++)
25 		S[i] = i;
26 	j = 0;
27 	kpos = 0;
28 	for (i = 0; i < 256; i++) {
29 		j = (j + S[i] + key[kpos]) & 0xff;
30 		kpos++;
31 		if (kpos >= keylen)
32 			kpos = 0;
33 		S_SWAP(i, j);
34 	}
35 
36 	/* Skip the start of the stream */
37 	i = j = 0;
38 	for (k = 0; k < skip; k++) {
39 		i = (i + 1) & 0xff;
40 		j = (j + S[i]) & 0xff;
41 		S_SWAP(i, j);
42 	}
43 
44 	/* Apply RC4 to data */
45 	pos = data;
46 	for (k = 0; k < data_len; k++) {
47 		i = (i + 1) & 0xff;
48 		j = (j + S[i]) & 0xff;
49 		S_SWAP(i, j);
50 		*pos++ ^= S[(S[i] + S[j]) & 0xff];
51 	}
52 
53 	return 0;
54 }
55