2 * THE BEER-WARE LICENSE
4 * <dan@FreeBSD.ORG> wrote this file. As long as you retain this notice you
5 * can do whatever you want with this stuff. If we meet some day, and you
6 * think this stuff is worth it, you can buy me a beer in return.
13 #include <sys/libkern.h>
15 #define ARC4_MAXRUNS 64
17 static u_int8_t arc4_i, arc4_j;
18 static int arc4_initialized = 0;
19 static int arc4_numruns = 0;
20 static u_int8_t arc4_sbox[256];
22 extern u_int read_random (void *, u_int);
25 arc4_swap(u_int8_t *a, u_int8_t *b)
38 arc4_randomstir (void)
43 r = read_random(key, sizeof(key));
44 /* if r == 0 || -1, just use what was on the stack */
47 for (n = r; n < sizeof(key); n++)
51 for (n = 0; n < 256; n++)
53 arc4_j = (arc4_j + arc4_sbox[n] + key[n]) % 256;
54 arc4_swap(&arc4_sbox[n], &arc4_sbox[arc4_j]);
59 * Initialize our S-box to its beginning defaults.
67 for (n = 0; n < 256; n++)
68 arc4_sbox[n] = (u_int8_t) n;
75 * Generate a random byte.
82 arc4_i = (arc4_i + 1) % 256;
83 arc4_j = (arc4_j + arc4_sbox[arc4_i]) % 256;
85 arc4_swap(&arc4_sbox[arc4_i], &arc4_sbox[arc4_j]);
87 arc4_t = (arc4_sbox[arc4_i] + arc4_sbox[arc4_j]) % 256;
88 return arc4_sbox[arc4_t];
96 /* Initialize array if needed. */
97 if (!arc4_initialized)
99 if (++arc4_numruns > ARC4_MAXRUNS)
105 ret = arc4_randbyte();
106 ret |= arc4_randbyte() << 8;
107 ret |= arc4_randbyte() << 16;
108 ret |= arc4_randbyte() << 24;