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.
10 * $FreeBSD: src/sys/libkern/arc4random.c,v 1.3.2.2 2001/09/17 07:06:50 silby Exp $
11 * $DragonFly: src/sys/libkern/arc4random.c,v 1.3 2006/09/03 17:31:55 dillon Exp $
14 #include <sys/types.h>
15 #include <sys/random.h>
16 #include <sys/libkern.h>
19 #define ARC4_MAXRUNS 16384
20 #define ARC4_RESEED_SECONDS 300
21 #define ARC4_KEYBYTES 32 /* 256 bit key */
23 static u_int8_t arc4_i
, arc4_j
;
24 static int arc4_initialized
= 0;
25 static int arc4_numruns
= 0;
26 static u_int8_t arc4_sbox
[256];
27 static struct timeval arc4_tv_nextreseed
;
29 static u_int8_t
arc4_randbyte(void);
32 arc4_swap(u_int8_t
*a
, u_int8_t
*b
)
45 arc4_randomstir (void)
51 * XXX read_random() returns unsafe numbers if the entropy
52 * device is not loaded -- MarkM.
54 r
= read_random_unlimited(key
, ARC4_KEYBYTES
);
55 /* If r == 0 || -1, just use what was on the stack. */
58 for (n
= r
; n
< sizeof(key
); n
++)
62 for (n
= 0; n
< 256; n
++) {
63 arc4_j
= (arc4_j
+ arc4_sbox
[n
] + key
[n
]) % 256;
64 arc4_swap(&arc4_sbox
[n
], &arc4_sbox
[arc4_j
]);
68 * Discard early keystream, as per recommendations in:
69 * "(Not So) Random Shuffles of RC4" by Ilya Mironov.
71 for (n
= 0; n
< 768*4; n
++)
74 /* Reset for next reseed cycle. */
75 getmicrotime(&arc4_tv_nextreseed
);
76 arc4_tv_nextreseed
.tv_sec
+= ARC4_RESEED_SECONDS
;
81 * Initialize our S-box to its beginning defaults.
89 for (n
= 0; n
< 256; n
++)
90 arc4_sbox
[n
] = (u_int8_t
) n
;
96 * Discard early keystream, as per recommendations in:
97 * "(Not So) Random Shuffles of RC4" by Ilya Mironov.
99 for (n
= 0; n
< 768*4; n
++)
104 * Generate a random byte.
111 arc4_i
= (arc4_i
+ 1) % 256;
112 arc4_j
= (arc4_j
+ arc4_sbox
[arc4_i
]) % 256;
114 arc4_swap(&arc4_sbox
[arc4_i
], &arc4_sbox
[arc4_j
]);
116 arc4_t
= (arc4_sbox
[arc4_i
] + arc4_sbox
[arc4_j
]) % 256;
117 return arc4_sbox
[arc4_t
];
124 struct timeval tv_now
;
126 /* Initialize array if needed. */
127 if (!arc4_initialized
)
130 getmicrotime(&tv_now
);
131 if ((++arc4_numruns
> ARC4_MAXRUNS
) ||
132 (tv_now
.tv_sec
> arc4_tv_nextreseed
.tv_sec
))
137 ret
= arc4_randbyte();
138 ret
|= arc4_randbyte() << 8;
139 ret
|= arc4_randbyte() << 16;
140 ret
|= arc4_randbyte() << 24;
146 karc4rand(void *ptr
, size_t len
)
149 struct timeval tv_now
;
153 /* Initialize array if needed. */
154 if (!arc4_initialized
)
157 getmicrotime(&tv_now
);
158 if ((++arc4_numruns
> ARC4_MAXRUNS
) ||
159 (tv_now
.tv_sec
> arc4_tv_nextreseed
.tv_sec
))
165 *p
++ = arc4_randbyte();