chiark / gitweb /
bee5cf1eeaf06bd5b154b453c7ebeabcb99562f9
[vbig.git] / Arcfour.cc
1 /* arcfour.c --- The arcfour stream cipher
2  * Copyright (C) 2000, 2001, 2002, 2003, 2005, 2006 Free Software
3  * Foundation, Inc.
4  *
5  * This file is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published
7  * by the Free Software Foundation; either version 2, or (at your
8  * option) any later version.
9  *
10  * This file is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this file; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
18  * 02110-1301, USA.
19  *
20  */
21 #include <config.h>
22 #include "Arcfour.h"
23
24 /** @brief Encrypt using Arcfour stream cipher
25  * @param context Context structure
26  * @param inbuf Input buffer
27  * @param outbuf Output buffer
28  * @param length Number of bytes in @p inbuf
29  *
30  * Copies from @p inbuf to @p outbuf, encrypting (or decrypting) using
31  * the stream controlled by @p context.
32  */
33 void Arcfour::stream(char *outbuf, size_t length) {
34   uint8_t i = idx_i;
35   uint8_t j = idx_j;
36   
37   for (; length > 0; length--) {
38     char t;
39
40     i++;
41     j += sbox[i];
42     t = sbox[i];
43     sbox[i] = sbox[j];
44     sbox[j] = t;
45     *outbuf++ = (sbox[(0U + sbox[i] + sbox[j]) % ARCFOUR_SBOX_SIZE]);
46   }
47
48   idx_i = i;
49   idx_j = j;
50 }
51
52 Arcfour::Arcfour(const char *key, size_t keylen) {
53   size_t i, j, k;
54   idx_i = idx_j = 0;
55   for (i = 0; i < ARCFOUR_SBOX_SIZE; i++)
56     sbox[i] = i;
57   for (i = j = k = 0; i < ARCFOUR_SBOX_SIZE; i++) {
58     char t;
59     j = (j + sbox[i] + key[k]) % ARCFOUR_SBOX_SIZE;
60     t = sbox[i];
61     sbox[i] = sbox[j];
62     sbox[j] = t;
63     if (++k == keylen)
64       k = 0;
65   }
66 }