OLD | NEW |
| (Empty) |
1 // Copyright 2005-2009 Google Inc. | |
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 // http://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 | |
16 #include "rc4.h" | |
17 | |
18 #include <inttypes.h> | |
19 | |
20 void RC4_setKey(RC4_CTX* ctx, const uint8_t* key, int len) { | |
21 uint8_t* S = ctx->S; | |
22 int i, j; | |
23 | |
24 for (i = 0; i < 256; ++i) { | |
25 S[i] = i; | |
26 } | |
27 | |
28 j = 0; | |
29 for (i = 0; i < 256; ++i) { | |
30 uint8_t tmp; | |
31 | |
32 j = (j + S[i] + key[i % len]) & 255; | |
33 | |
34 tmp = S[i]; | |
35 S[i] = S[j]; | |
36 S[j] = tmp; | |
37 } | |
38 | |
39 ctx->i = 0; | |
40 ctx->j = 0; | |
41 } | |
42 | |
43 void RC4_crypt(RC4_CTX* ctx, | |
44 const uint8_t *in, | |
45 uint8_t* out, | |
46 int len) { | |
47 uint8_t i = ctx->i; | |
48 uint8_t j = ctx->j; | |
49 uint8_t* S = ctx->S; | |
50 | |
51 int n; | |
52 | |
53 for (n = 0; n < len; ++n) { | |
54 uint8_t tmp; | |
55 | |
56 i = (i + 1) & 255; | |
57 j = (j + S[i]) & 255; | |
58 | |
59 tmp = S[i]; | |
60 S[i] = S[j]; | |
61 S[j] = tmp; | |
62 | |
63 if (in) { | |
64 if (out) { | |
65 out[n] = in[n] ^ S[(S[i] + S[j]) & 255]; | |
66 } | |
67 } else { | |
68 if (out) { | |
69 out[n] = S[(S[i] + S[j]) & 255]; | |
70 } | |
71 } | |
72 } | |
73 | |
74 ctx->i = i; | |
75 ctx->j = j; | |
76 } | |
77 | |
78 void RC4_discard(RC4_CTX* ctx, int len) { | |
79 RC4_crypt(ctx, 0, 0, len); | |
80 } | |
81 | |
82 void RC4_stream(RC4_CTX* ctx, uint8_t* out, int len) { | |
83 RC4_crypt(ctx, 0, out, len); | |
84 } | |
OLD | NEW |