Coverage Report

Created: 2023-02-22 06:14

/src/nettle-with-mini-gmp/arcfour.c
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
26.1k
#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
102
{
48
102
  unsigned i, j, k;
49
  
50
102
  assert(length >= ARCFOUR_MIN_KEY_SIZE);
51
102
  assert(length <= ARCFOUR_MAX_KEY_SIZE);
52
53
  /* Initialize context */
54
26.2k
  for (i = 0; i<256; i++)
55
26.1k
    ctx->S[i] = i;
56
57
26.2k
  for (i = j = k = 0; i<256; i++)
58
26.1k
    {
59
26.1k
      j += ctx->S[i] + key[k]; j &= 0xff;
60
26.1k
      SWAP(ctx->S[i], ctx->S[j]);
61
      /* Repeat key as needed */
62
26.1k
      k = (k + 1) % length;
63
26.1k
    }
64
102
  ctx->i = ctx->j = 0;
65
102
}
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
102
{
78
102
  register uint8_t i, j;
79
102
  register int si, sj;
80
81
102
  i = ctx->i; j = ctx->j;
82
2.34k
  while(length--)
83
2.24k
    {
84
2.24k
      i++; i &= 0xff;
85
2.24k
      si = ctx->S[i];
86
2.24k
      j += si; j &= 0xff;
87
2.24k
      sj = ctx->S[i] = ctx->S[j];
88
2.24k
      ctx->S[j] = si;
89
2.24k
      *dst++ = *src++ ^ ctx->S[ (si + sj) & 0xff ];
90
2.24k
    }
91
102
  ctx->i = i; ctx->j = j;
92
102
}