1 /* $FreeBSD: src/lib/libc/gen/arc4random.c,v 1.4 2000/01/27 23:06:13 jasone Exp $ */
2 /* $DragonFly: src/lib/libc/gen/arc4random.c,v 1.5 2005/01/31 22:29:15 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.
29 #include "namespace.h"
33 #include <sys/types.h>
35 #include "un-namespace.h"
43 static int rs_initialized;
44 static struct arc4_stream rs;
46 static inline u_int8_t arc4_getbyte(struct arc4_stream *);
50 struct arc4_stream *as;
54 for (n = 0; n < 256; n++)
61 arc4_addrandom(as, dat, datlen)
62 struct arc4_stream *as;
70 for (n = 0; n < 256; n++) {
73 as->j = (as->j + si + dat[n % datlen]);
74 as->s[as->i] = as->s[as->j];
81 struct arc4_stream *as;
87 u_int8_t rnd[128 - sizeof(struct timeval) - sizeof(pid_t)];
90 gettimeofday(&rdat.tv, NULL);
92 fd = _open("/dev/urandom", O_RDONLY, 0);
94 (void) _read(fd, rdat.rnd, sizeof(rdat.rnd));
97 /* fd < 0? Ah, what the heck. We'll just take whatever was on the
100 arc4_addrandom(as, (void *) &rdat, sizeof(rdat));
103 * Throw away the first N bytes of output, as suggested in the
104 * paper "Weaknesses in the Key Scheduling Algorithm of RC4"
105 * by Fluher, Mantin, and Shamir. N=1024 is based on
106 * suggestions in the paper "(Not So) Random Shuffles of RC4"
109 for (n = 0; n < 1024; n++)
113 static inline u_int8_t
114 arc4_getbyte(struct arc4_stream *as)
120 as->j = (as->j + si);
124 return (as->s[(si + sj) & 0xff]);
127 static inline u_int32_t
129 struct arc4_stream *as;
132 val = arc4_getbyte(as) << 24;
133 val |= arc4_getbyte(as) << 16;
134 val |= arc4_getbyte(as) << 8;
135 val |= arc4_getbyte(as);
142 if (!rs_initialized) {
150 arc4random_addrandom(dat, datlen)
156 arc4_addrandom(&rs, dat, datlen);
164 return arc4_getword(&rs);
168 /*-------- Test code for i386 --------*/
170 #include <machine/pctr.h>
172 main(int argc, char **argv)
174 const int iter = 1000000;
179 for (i = 0; i < iter; i++)
184 printf("%qd cycles\n", v);