Line data Source code
1 : /* $OpenBSD: arc4.c,v 1.3 2007/09/11 12:07:05 djm Exp $ */
2 : /*
3 : * Copyright (c) 2003 Markus Friedl <markus@openbsd.org>
4 : *
5 : * Permission to use, copy, modify, and distribute this software for any
6 : * purpose with or without fee is hereby granted, provided that the above
7 : * copyright notice and this permission notice appear in all copies.
8 : *
9 : * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 : * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 : * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 : * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 : * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 : * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 : * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16 : */
17 :
18 : #include <sys/types.h>
19 :
20 : #include <crypto/arc4.h>
21 :
22 : #define RC4SWAP(x,y) \
23 : do { \
24 : u_int8_t t = ctx->state[x]; \
25 : ctx->state[x] = ctx->state[y]; \
26 : ctx->state[y] = t; \
27 : } while(0)
28 :
29 : void
30 0 : rc4_keysetup(struct rc4_ctx *ctx, u_char *key, u_int32_t klen)
31 : {
32 : u_int8_t x, y;
33 : u_int32_t i;
34 :
35 : x = y = 0;
36 0 : for (i = 0; i < RC4STATE; i++)
37 0 : ctx->state[i] = i;
38 0 : for (i = 0; i < RC4STATE; i++) {
39 0 : y = (key[x] + ctx->state[i] + y) & (RC4STATE - 1);
40 0 : RC4SWAP(i, y);
41 0 : x = (x + 1) % klen;
42 : }
43 0 : ctx->x = ctx->y = 0;
44 0 : }
45 :
46 : void
47 0 : rc4_crypt(struct rc4_ctx *ctx, u_char *src, u_char *dst,
48 : u_int32_t len)
49 : {
50 : u_int32_t i;
51 :
52 0 : for (i = 0; i < len; i++) {
53 0 : ctx->x = (ctx->x + 1) & (RC4STATE - 1);
54 0 : ctx->y = (ctx->state[ctx->x] + ctx->y) & (RC4STATE - 1);
55 0 : RC4SWAP(ctx->x, ctx->y);
56 0 : dst[i] = src[i] ^ ctx->state[
57 0 : (ctx->state[ctx->x] + ctx->state[ctx->y]) & (RC4STATE - 1)];
58 : }
59 0 : }
60 :
61 : void
62 0 : rc4_getbytes(struct rc4_ctx *ctx, u_char *dst, u_int32_t len)
63 : {
64 : u_int32_t i;
65 :
66 0 : for (i = 0; i < len; i++) {
67 0 : ctx->x = (ctx->x + 1) & (RC4STATE - 1);
68 0 : ctx->y = (ctx->state[ctx->x] + ctx->y) & (RC4STATE - 1);
69 0 : RC4SWAP(ctx->x, ctx->y);
70 0 : dst[i] = ctx->state[
71 0 : (ctx->state[ctx->x] + ctx->state[ctx->y]) & (RC4STATE - 1)];
72 : }
73 0 : }
74 :
75 : void
76 0 : rc4_skip(struct rc4_ctx *ctx, u_int32_t len)
77 : {
78 0 : for (; len > 0; len--) {
79 0 : ctx->x = (ctx->x + 1) & (RC4STATE - 1);
80 0 : ctx->y = (ctx->state[ctx->x] + ctx->y) & (RC4STATE - 1);
81 0 : RC4SWAP(ctx->x, ctx->y);
82 : }
83 0 : }
|