6 /* RC4-based pseudo-random number generator (PRNG).
8 RC4 is a stream cipher. We're not using it here for its
9 cryptographic properties, but because it is easy to implement
10 and its output is plenty random for non-cryptographic
13 See http://en.wikipedia.org/wiki/RC4_(cipher) for information
17 static uint8_t s[256]; /* S[]. */
18 static uint8_t s_i, s_j; /* i, j. */
20 /* Already initialized? */
23 /* Swaps the bytes pointed to by A and B. */
25 swap_byte (uint8_t *a, uint8_t *b)
32 /* Initializes or reinitializes the PRNG with the given SEED. */
34 random_init (unsigned seed)
36 uint8_t *seedp = (uint8_t *) &seed;
40 for (i = 0; i < 256; i++)
42 for (i = j = 0; i < 256; i++)
44 j += s[i] + seedp[i % sizeof seed];
45 swap_byte (s + i, s + j);
52 /* Writes SIZE random bytes into BUF. */
54 random_bytes (void *buf_, size_t size)
61 for (buf = buf_; size-- > 0; buf++)
67 swap_byte (s + s_i, s + s_j);
69 s_k = s[s_i] + s[s_j];
74 /* Returns a pseudo-random unsigned long.
75 Use random_ulong() % n to obtain a random number in the range
81 random_bytes (&ul, sizeof ul);