Line | Count | Source (jump to first uncovered line) |
1 | | /* arcfour.c |
2 | | |
3 | | The arcfour/rc4 stream cipher. |
4 | | |
5 | | Copyright (C) 2001, 2014 Niels Möller |
6 | | |
7 | | This file is part of GNU Nettle. |
8 | | |
9 | | GNU Nettle is free software: you can redistribute it and/or |
10 | | modify it under the terms of either: |
11 | | |
12 | | * the GNU Lesser General Public License as published by the Free |
13 | | Software Foundation; either version 3 of the License, or (at your |
14 | | option) any later version. |
15 | | |
16 | | or |
17 | | |
18 | | * the GNU General Public License as published by the Free |
19 | | Software Foundation; either version 2 of the License, or (at your |
20 | | option) any later version. |
21 | | |
22 | | or both in parallel, as here. |
23 | | |
24 | | GNU Nettle is distributed in the hope that it will be useful, |
25 | | but WITHOUT ANY WARRANTY; without even the implied warranty of |
26 | | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
27 | | General Public License for more details. |
28 | | |
29 | | You should have received copies of the GNU General Public License and |
30 | | the GNU Lesser General Public License along with this program. If |
31 | | not, see http://www.gnu.org/licenses/. |
32 | | */ |
33 | | |
34 | | #if HAVE_CONFIG_H |
35 | | # include "config.h" |
36 | | #endif |
37 | | |
38 | | #include <assert.h> |
39 | | |
40 | | #include "arcfour.h" |
41 | | |
42 | 0 | #define SWAP(a,b) do { int _t = a; a = b; b = _t; } while(0) |
43 | | |
44 | | void |
45 | | arcfour_set_key(struct arcfour_ctx *ctx, |
46 | | size_t length, const uint8_t *key) |
47 | 0 | { |
48 | 0 | unsigned i, j, k; |
49 | | |
50 | 0 | assert(length >= ARCFOUR_MIN_KEY_SIZE); |
51 | 0 | assert(length <= ARCFOUR_MAX_KEY_SIZE); |
52 | | |
53 | | /* Initialize context */ |
54 | 0 | for (i = 0; i<256; i++) |
55 | 0 | ctx->S[i] = i; |
56 | |
|
57 | 0 | for (i = j = k = 0; i<256; i++) |
58 | 0 | { |
59 | 0 | j += ctx->S[i] + key[k]; j &= 0xff; |
60 | 0 | SWAP(ctx->S[i], ctx->S[j]); |
61 | | /* Repeat key as needed */ |
62 | 0 | k = (k + 1) % length; |
63 | 0 | } |
64 | 0 | ctx->i = ctx->j = 0; |
65 | 0 | } |
66 | | |
67 | | void |
68 | | arcfour128_set_key(struct arcfour_ctx *ctx, const uint8_t *key) |
69 | 0 | { |
70 | 0 | arcfour_set_key (ctx, ARCFOUR128_KEY_SIZE, key); |
71 | 0 | } |
72 | | |
73 | | void |
74 | | arcfour_crypt(struct arcfour_ctx *ctx, |
75 | | size_t length, uint8_t *dst, |
76 | | const uint8_t *src) |
77 | 0 | { |
78 | 0 | register uint8_t i, j; |
79 | 0 | register int si, sj; |
80 | |
|
81 | 0 | i = ctx->i; j = ctx->j; |
82 | 0 | while(length--) |
83 | 0 | { |
84 | 0 | i++; i &= 0xff; |
85 | 0 | si = ctx->S[i]; |
86 | 0 | j += si; j &= 0xff; |
87 | 0 | sj = ctx->S[i] = ctx->S[j]; |
88 | 0 | ctx->S[j] = si; |
89 | 0 | *dst++ = *src++ ^ ctx->S[ (si + sj) & 0xff ]; |
90 | 0 | } |
91 | 0 | ctx->i = i; ctx->j = j; |
92 | 0 | } |