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
rc4_keysetup(struct rc4_ctx * ctx,u_char * key,u_int32_t klen)30 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 for (i = 0; i < RC4STATE; i++)
37 ctx->state[i] = i;
38 for (i = 0; i < RC4STATE; i++) {
39 y = (key[x] + ctx->state[i] + y) & (RC4STATE - 1);
40 RC4SWAP(i, y);
41 x = (x + 1) % klen;
42 }
43 ctx->x = ctx->y = 0;
44 }
45
46 void
rc4_crypt(struct rc4_ctx * ctx,u_char * src,u_char * dst,u_int32_t len)47 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 for (i = 0; i < len; i++) {
53 ctx->x = (ctx->x + 1) & (RC4STATE - 1);
54 ctx->y = (ctx->state[ctx->x] + ctx->y) & (RC4STATE - 1);
55 RC4SWAP(ctx->x, ctx->y);
56 dst[i] = src[i] ^ ctx->state[
57 (ctx->state[ctx->x] + ctx->state[ctx->y]) & (RC4STATE - 1)];
58 }
59 }
60
61 void
rc4_getbytes(struct rc4_ctx * ctx,u_char * dst,u_int32_t len)62 rc4_getbytes(struct rc4_ctx *ctx, u_char *dst, u_int32_t len)
63 {
64 u_int32_t i;
65
66 for (i = 0; i < len; i++) {
67 ctx->x = (ctx->x + 1) & (RC4STATE - 1);
68 ctx->y = (ctx->state[ctx->x] + ctx->y) & (RC4STATE - 1);
69 RC4SWAP(ctx->x, ctx->y);
70 dst[i] = ctx->state[
71 (ctx->state[ctx->x] + ctx->state[ctx->y]) & (RC4STATE - 1)];
72 }
73 }
74
75 void
rc4_skip(struct rc4_ctx * ctx,u_int32_t len)76 rc4_skip(struct rc4_ctx *ctx, u_int32_t len)
77 {
78 for (; len > 0; len--) {
79 ctx->x = (ctx->x + 1) & (RC4STATE - 1);
80 ctx->y = (ctx->state[ctx->x] + ctx->y) & (RC4STATE - 1);
81 RC4SWAP(ctx->x, ctx->y);
82 }
83 }
84