arcfour.c 1.66 KB
Newer Older
Niels Möller's avatar
Niels Möller committed
1
/* arcfour.c
Niels Möller's avatar
Niels Möller committed
2
 *
Niels Möller's avatar
Niels Möller committed
3
 * The arcfour/rc4 stream cipher.
Niels Möller's avatar
Niels Möller committed
4 5
 */

Niels Möller's avatar
Niels Möller committed
6
/* nettle, low-level cryptographics library
Niels Möller's avatar
Niels Möller committed
7
 *
8
 * Copyright (C) 2001, 2014 Niels Möller
Niels Möller's avatar
Niels Möller committed
9 10 11 12 13 14
 *  
 * The nettle library is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or (at your
 * option) any later version.
 * 
Niels Möller's avatar
Niels Möller committed
15
 * The nettle library is distributed in the hope that it will be useful, but
Niels Möller's avatar
Niels Möller committed
16 17 18 19 20
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
 * License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
Niels Möller's avatar
Niels Möller committed
21
 * along with the nettle library; see the file COPYING.LIB.  If not, write to
22 23
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02111-1301, USA.
Niels Möller's avatar
Niels Möller committed
24 25
 */

26 27 28
#if HAVE_CONFIG_H
# include "config.h"
#endif
Niels Möller's avatar
Niels Möller committed
29

30 31
#include <assert.h>

32 33
#include "arcfour.h"

Niels Möller's avatar
Niels Möller committed
34 35
#define SWAP(a,b) do { int _t = a; a = b; b = _t; } while(0)

Niels Möller's avatar
Niels Möller committed
36 37
void
arcfour_set_key(struct arcfour_ctx *ctx,
38
		size_t length, const uint8_t *key)
39
{
Niels Möller's avatar
Niels Möller committed
40 41 42 43
  unsigned i, j, k;
  
  assert(length >= ARCFOUR_MIN_KEY_SIZE);
  assert(length <= ARCFOUR_MAX_KEY_SIZE);
44 45 46 47 48

  /* Initialize context */
  for (i = 0; i<256; i++)
    ctx->S[i] = i;

Niels Möller's avatar
Niels Möller committed
49
  for (i = j = k = 0; i<256; i++)
50 51 52
    {
      j += ctx->S[i] + key[k]; j &= 0xff;
      SWAP(ctx->S[i], ctx->S[j]);
Niels Möller's avatar
Niels Möller committed
53 54
      /* Repeat key as needed */
      k = (k + 1) % length;
55
    }
Niels Möller's avatar
Niels Möller committed
56
  ctx->i = ctx->j = 0;
57 58
}

59 60 61 62 63
void
arcfour128_set_key(struct arcfour_ctx *ctx, const uint8_t *key)
{
  arcfour_set_key (ctx, ARCFOUR128_KEY_SIZE, key);
}