Add arcfour module.
[gnulib.git] / lib / arcfour.c
1 /* arcfour.c --- The arcfour stream cipher
2  * Copyright (C) 2000, 2001, 2002, 2003, 2005 Free Software Foundation, Inc.
3  *
4  * This file is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published
6  * by the Free Software Foundation; either version 2, or (at your
7  * option) any later version.
8  *
9  * This file is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this file; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
17  * 02110-1301, USA.
18  *
19  */
20
21 /* Code from Libgcrypt adapted for gnulib by Simon Josefsson. */
22
23 /*
24  * For a description of the algorithm, see:
25  *   Bruce Schneier: Applied Cryptography. John Wiley & Sons, 1996.
26  *   ISBN 0-471-11709-9. Pages 397 ff.
27  */
28
29 #ifdef HAVE_CONFIG_H
30 # include <config.h>
31 #endif
32
33 #include "arcfour.h"
34
35 void
36 arcfour_stream (arcfour_context * context, const char *inbuf, char *outbuf,
37                 size_t length)
38 {
39   size_t i = context->idx_i;
40   size_t j = context->idx_j;
41   char *sbox = context->sbox;
42
43   for (; length > 0; length--)
44     {
45       char t;
46
47       i = (i + 1) % ARCFOUR_SBOX_SIZE;
48       j = (j + sbox[i]) % ARCFOUR_SBOX_SIZE;
49       t = sbox[i];
50       sbox[i] = sbox[j];
51       sbox[j] = t;
52       *outbuf++ = (*inbuf++
53                    ^ sbox[(0U + sbox[i] + sbox[j]) % ARCFOUR_SBOX_SIZE]);
54     }
55
56   context->idx_i = i;
57   context->idx_j = j;
58 }
59
60 void
61 arcfour_setkey (arcfour_context * context, const char *key, size_t keylen)
62 {
63   size_t i, j, k;
64   char *sbox = context->sbox;
65
66   context->idx_i = context->idx_j = 0;
67   for (i = 0; i < ARCFOUR_SBOX_SIZE; i++)
68     sbox[i] = i;
69   for (i = j = k = 0; i < ARCFOUR_SBOX_SIZE; i++)
70     {
71       char t;
72       j = (j + sbox[i] + key[k]) % ARCFOUR_SBOX_SIZE;
73       t = sbox[i];
74       sbox[i] = sbox[j];
75       sbox[j] = t;
76       if (++k == keylen)
77         k = 0;
78     }
79 }