1 // Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include <openssl/rc4.h>
16 
17 
RC4(RC4_KEY * key,size_t len,const uint8_t * in,uint8_t * out)18 void RC4(RC4_KEY *key, size_t len, const uint8_t *in, uint8_t *out) {
19   uint32_t x = key->x;
20   uint32_t y = key->y;
21   uint32_t *d = key->data;
22 
23   for (size_t i = 0; i < len; i++) {
24     x = (x + 1) & 0xff;
25     uint32_t tx = d[x];
26     y = (tx + y) & 0xff;
27     uint32_t ty = d[y];
28     d[x] = ty;
29     d[y] = tx;
30     out[i] = d[(tx + ty) & 0xff] ^ in[i];
31   }
32 
33   key->x = x;
34   key->y = y;
35 }
36 
RC4_set_key(RC4_KEY * rc4key,unsigned len,const uint8_t * key)37 void RC4_set_key(RC4_KEY *rc4key, unsigned len, const uint8_t *key) {
38   uint32_t *d = &rc4key->data[0];
39   rc4key->x = 0;
40   rc4key->y = 0;
41 
42   for (unsigned i = 0; i < 256; i++) {
43     d[i] = i;
44   }
45 
46   unsigned id1 = 0, id2 = 0;
47   for (unsigned i = 0; i < 256; i++) {
48     uint32_t tmp = d[i];
49     id2 = (key[id1] + tmp + id2) & 0xff;
50     if (++id1 == len) {
51       id1 = 0;
52     }
53     d[i] = d[id2];
54     d[id2] = tmp;
55   }
56 }
57