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.7 2005/11/13 01:07:42 swildner 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 u_int8_t
arc4_getbyte(struct arc4_stream
*);
49 arc4_init(struct arc4_stream
*as
)
53 for (n
= 0; n
< 256; n
++)
60 arc4_addrandom(struct arc4_stream
*as
, u_char
*dat
, size_t datlen
)
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
];
76 arc4_stir(struct arc4_stream
*as
)
82 u_int8_t rnd
[128 - sizeof(struct timeval
) - sizeof(pid_t
)];
85 gettimeofday(&rdat
.tv
, NULL
);
87 fd
= _open("/dev/urandom", O_RDONLY
, 0);
89 _read(fd
, rdat
.rnd
, sizeof(rdat
.rnd
));
92 /* fd < 0? Ah, what the heck. We'll just take whatever was on the
95 arc4_addrandom(as
, (void *) &rdat
, sizeof(rdat
));
98 * Throw away the first N bytes of output, as suggested in the
99 * paper "Weaknesses in the Key Scheduling Algorithm of RC4"
100 * by Fluher, Mantin, and Shamir. N=1024 is based on
101 * suggestions in the paper "(Not So) Random Shuffles of RC4"
104 for (n
= 0; n
< 1024; n
++)
109 arc4_getbyte(struct arc4_stream
*as
)
115 as
->j
= (as
->j
+ si
);
119 return (as
->s
[(si
+ sj
) & 0xff]);
123 arc4_getword(struct arc4_stream
*as
)
126 val
= arc4_getbyte(as
) << 24;
127 val
|= arc4_getbyte(as
) << 16;
128 val
|= arc4_getbyte(as
) << 8;
129 val
|= arc4_getbyte(as
);
134 arc4random_stir(void)
136 if (!rs_initialized
) {
144 arc4random_addrandom(uint8_t *dat
, size_t datlen
)
148 arc4_addrandom(&rs
, dat
, datlen
);
156 return arc4_getword(&rs
);
160 /*-------- Test code for i386 --------*/
162 #include <machine/pctr.h>
164 main(int argc
, char **argv
)
166 const int iter
= 1000000;
171 for (i
= 0; i
< iter
; i
++)
176 printf("%qd cycles\n", v
);