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 the PRNG with the given SEED.
33 Does nothing if the PRNG has already been initialized. */
35 random_init (unsigned seed)
37 uint8_t *seedp = (uint8_t *) &seed;
44 for (i = 0; i < 256; i++)
46 for (i = j = 0; i < 256; i++)
48 j += s[i] + seedp[i % sizeof seed];
49 swap_byte (s + i, s + j);
56 /* Writes SIZE random bytes into BUF. */
58 random_bytes (void *buf_, size_t size)
63 for (buf = buf_; size-- > 0; buf++)
69 swap_byte (s + s_i, s + s_j);
71 s_k = s[s_i] + s[s_j];
76 /* Returns a pseudo-random unsigned long. */
81 random_bytes (&ul, sizeof ul);