1 /* $FreeBSD: src/lib/libc/gen/arc4random.c,v 1.4 2000/01/27 23:06:13 jasone Exp $ */
2 /* $DragonFly: src/lib/libcr/gen/Attic/arc4random.c,v 1.2 2003/06/17 04:26:42 dillon Exp $ */
5 * Arc4 random number generator for OpenBSD.
6 * Copyright 1996 David Mazieres <dm@lcs.mit.edu>.
8 * Modification and redistribution in source and binary forms is
9 * permitted provided that due credit is given to the author and the
10 * OpenBSD project (for instance by leaving this copyright notice
15 * This code is derived from section 17.1 of Applied Cryptography,
16 * second edition, which describes a stream cipher allegedly
17 * compatible with RSA Labs "RC4" cipher (the actual description of
18 * which is a trade secret). The same algorithm is used as a stream
19 * cipher called "arcfour" in Tatu Ylonen's ssh package.
21 * Here the stream cipher has been modified always to include the time
22 * when initializing the state. That makes it impossible to
23 * regenerate the same random sequence twice, so this can't be used
24 * for encryption, but will generate good random numbers.
26 * RC4 is a registered trademark of RSA Laboratories.
32 #include <sys/types.h>
41 static int rs_initialized;
42 static struct arc4_stream rs;
46 struct arc4_stream *as;
50 for (n = 0; n < 256; n++)
57 arc4_addrandom(as, dat, datlen)
58 struct arc4_stream *as;
66 for (n = 0; n < 256; n++) {
69 as->j = (as->j + si + dat[n % datlen]);
70 as->s[as->i] = as->s[as->j];
77 struct arc4_stream *as;
83 u_int8_t rnd[128 - sizeof(struct timeval) - sizeof(pid_t)];
86 gettimeofday(&rdat.tv, NULL);
88 fd = _open("/dev/urandom", O_RDONLY, 0);
90 (void) _read(fd, rdat.rnd, sizeof(rdat.rnd));
93 /* fd < 0? Ah, what the heck. We'll just take whatever was on the
96 arc4_addrandom(as, (void *) &rdat, sizeof(rdat));
99 static inline u_int8_t
101 struct arc4_stream *as;
107 as->j = (as->j + si);
111 return (as->s[(si + sj) & 0xff]);
114 static inline u_int32_t
116 struct arc4_stream *as;
119 val = arc4_getbyte(as) << 24;
120 val |= arc4_getbyte(as) << 16;
121 val |= arc4_getbyte(as) << 8;
122 val |= arc4_getbyte(as);
129 if (!rs_initialized) {
137 arc4random_addrandom(dat, datlen)
143 arc4_addrandom(&rs, dat, datlen);
151 return arc4_getword(&rs);
155 /*-------- Test code for i386 --------*/
157 #include <machine/pctr.h>
159 main(int argc, char **argv)
161 const int iter = 1000000;
166 for (i = 0; i < iter; i++)
171 printf("%qd cycles\n", v);