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
++)
64 arc4_j
= (arc4_j
+ arc4_sbox
[n
] + key
[n
]) % 256;
65 arc4_swap(&arc4_sbox
[n
], &arc4_sbox
[arc4_j
]);
68 /* Reset for next reseed cycle. */
69 getmicrotime(&arc4_tv_nextreseed
);
70 arc4_tv_nextreseed
.tv_sec
+= ARC4_RESEED_SECONDS
;
75 * Initialize our S-box to its beginning defaults.
83 for (n
= 0; n
< 256; n
++)
84 arc4_sbox
[n
] = (u_int8_t
) n
;
90 * Throw away the first N words of output, as suggested in the
91 * paper "Weaknesses in the Key Scheduling Algorithm of RC4"
92 * by Fluher, Mantin, and Shamir. (N = 256 in our case.)
94 for (n
= 0; n
< 256*4; n
++)
99 * Generate a random byte.
106 arc4_i
= (arc4_i
+ 1) % 256;
107 arc4_j
= (arc4_j
+ arc4_sbox
[arc4_i
]) % 256;
109 arc4_swap(&arc4_sbox
[arc4_i
], &arc4_sbox
[arc4_j
]);
111 arc4_t
= (arc4_sbox
[arc4_i
] + arc4_sbox
[arc4_j
]) % 256;
112 return arc4_sbox
[arc4_t
];
119 struct timeval tv_now
;
121 /* Initialize array if needed. */
122 if (!arc4_initialized
)
125 getmicrotime(&tv_now
);
126 if ((++arc4_numruns
> ARC4_MAXRUNS
) ||
127 (tv_now
.tv_sec
> arc4_tv_nextreseed
.tv_sec
))
132 ret
= arc4_randbyte();
133 ret
|= arc4_randbyte() << 8;
134 ret
|= arc4_randbyte() << 16;
135 ret
|= arc4_randbyte() << 24;