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.3 2004/07/05 17:30:59 eirikn 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;
44 static inline u_int8_t arc4_getbyte(struct arc4_stream *);
48 struct arc4_stream *as;
52 for (n = 0; n < 256; n++)
59 arc4_addrandom(as, dat, datlen)
60 struct arc4_stream *as;
68 for (n = 0; n < 256; n++) {
71 as->j = (as->j + si + dat[n % datlen]);
72 as->s[as->i] = as->s[as->j];
79 struct arc4_stream *as;
85 u_int8_t rnd[128 - sizeof(struct timeval) - sizeof(pid_t)];
88 gettimeofday(&rdat.tv, NULL);
90 fd = _open("/dev/urandom", O_RDONLY, 0);
92 (void) _read(fd, rdat.rnd, sizeof(rdat.rnd));
95 /* fd < 0? Ah, what the heck. We'll just take whatever was on the
98 arc4_addrandom(as, (void *) &rdat, sizeof(rdat));
101 * Throw away the first N bytes of output, as suggested in the
102 * paper "Weaknesses in the Key Scheduling Algorithm of RC4"
103 * by Fluher, Mantin, and Shamir. N=1024 is based on
104 * suggestions in the paper "(Not So) Random Shuffles of RC4"
107 for (n = 0; n < 1024; n++)
111 static inline u_int8_t
112 arc4_getbyte(struct arc4_stream *as)
118 as->j = (as->j + si);
122 return (as->s[(si + sj) & 0xff]);
125 static inline u_int32_t
127 struct arc4_stream *as;
130 val = arc4_getbyte(as) << 24;
131 val |= arc4_getbyte(as) << 16;
132 val |= arc4_getbyte(as) << 8;
133 val |= arc4_getbyte(as);
140 if (!rs_initialized) {
148 arc4random_addrandom(dat, datlen)
154 arc4_addrandom(&rs, dat, datlen);
162 return arc4_getword(&rs);
166 /*-------- Test code for i386 --------*/
168 #include <machine/pctr.h>
170 main(int argc, char **argv)
172 const int iter = 1000000;
177 for (i = 0; i < iter; i++)
182 printf("%qd cycles\n", v);