xref: /freebsd/sys/libkern/arc4random.c (revision e2059d0b)
1 /*-
2  * THE BEER-WARE LICENSE
3  *
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.
7  *
8  * Dan Moschuk
9  *
10  * $FreeBSD$
11  */
12 
13 #include <sys/types.h>
14 #include <sys/random.h>
15 #include <sys/libkern.h>
16 
17 #define	ARC4_MAXRUNS 64
18 
19 static u_int8_t arc4_i, arc4_j;
20 static int arc4_initialized = 0;
21 static int arc4_numruns = 0;
22 static u_int8_t arc4_sbox[256];
23 
24 static __inline void
25 arc4_swap(u_int8_t *a, u_int8_t *b)
26 {
27 	u_int8_t c;
28 
29 	c = *a;
30 	*a = *b;
31 	*b = c;
32 }
33 
34 /*
35  * Stir our S-box.
36  */
37 static void
38 arc4_randomstir (void)
39 {
40 	u_int8_t key[256];
41 	int r, n;
42 
43 	/* r = read_random(key, sizeof(key)); */
44 	r = 0; /* XXX MarkM - revisit this when /dev/random is done */
45 	/* if r == 0 || -1, just use what was on the stack */
46 	if (r > 0)
47 	{
48 		for (n = r; n < sizeof(key); n++)
49 			key[n] = key[n % r];
50 	}
51 
52 	for (n = 0; n < 256; n++)
53 	{
54 		arc4_j = (arc4_j + arc4_sbox[n] + key[n]) % 256;
55 		arc4_swap(&arc4_sbox[n], &arc4_sbox[arc4_j]);
56 	}
57 }
58 
59 /*
60  * Initialize our S-box to its beginning defaults.
61  */
62 static void
63 arc4_init(void)
64 {
65 	int n;
66 
67 	arc4_i = arc4_j = 0;
68 	for (n = 0; n < 256; n++)
69 		arc4_sbox[n] = (u_int8_t) n;
70 
71 	arc4_randomstir();
72 	arc4_initialized = 1;
73 }
74 
75 /*
76  * Generate a random byte.
77  */
78 static u_int8_t
79 arc4_randbyte(void)
80 {
81 	u_int8_t arc4_t;
82 
83 	arc4_i = (arc4_i + 1) % 256;
84 	arc4_j = (arc4_j + arc4_sbox[arc4_i]) % 256;
85 
86 	arc4_swap(&arc4_sbox[arc4_i], &arc4_sbox[arc4_j]);
87 
88 	arc4_t = (arc4_sbox[arc4_i] + arc4_sbox[arc4_j]) % 256;
89 	return arc4_sbox[arc4_t];
90 }
91 
92 u_int32_t
93 arc4random(void)
94 {
95 	u_int32_t ret;
96 
97 	/* Initialize array if needed. */
98 	if (!arc4_initialized)
99 		arc4_init();
100 	if (++arc4_numruns > ARC4_MAXRUNS)
101 	{
102 		arc4_randomstir();
103 		arc4_numruns = 0;
104 	}
105 
106 	ret = arc4_randbyte();
107 	ret |= arc4_randbyte() << 8;
108 	ret |= arc4_randbyte() << 16;
109 	ret |= arc4_randbyte() << 24;
110 
111 	return ret;
112 }
113