From 6582c665d6b882dad8329e05749fbcf119f1ab88 Mon Sep 17 00:00:00 2001 From: Akinobu Mita Date: Mon, 17 Dec 2012 16:04:25 -0800 Subject: prandom: introduce prandom_bytes() and prandom_bytes_state() Add functions to get the requested number of pseudo-random bytes. The difference from get_random_bytes() is that it generates pseudo-random numbers by prandom_u32(). It doesn't consume the entropy pool, and the sequence is reproducible if the same rnd_state is used. So it is suitable for generating random bytes for testing. Signed-off-by: Akinobu Mita Cc: "Theodore Ts'o" Cc: Artem Bityutskiy Cc: Adrian Hunter Cc: David Woodhouse Cc: Eilon Greenstein Cc: David Laight Cc: Michel Lespinasse Cc: Robert Love Cc: Valdis Kletnieks Signed-off-by: Andrew Morton Signed-off-by: Linus Torvalds --- lib/random32.c | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) (limited to 'lib/random32.c') diff --git a/lib/random32.c b/lib/random32.c index d1830fade915..52280d5526be 100644 --- a/lib/random32.c +++ b/lib/random32.c @@ -77,6 +77,55 @@ u32 prandom_u32(void) } EXPORT_SYMBOL(prandom_u32); +/* + * prandom_bytes_state - get the requested number of pseudo-random bytes + * + * @state: pointer to state structure holding seeded state. + * @buf: where to copy the pseudo-random bytes to + * @bytes: the requested number of bytes + * + * This is used for pseudo-randomness with no outside seeding. + * For more random results, use prandom_bytes(). + */ +void prandom_bytes_state(struct rnd_state *state, void *buf, int bytes) +{ + unsigned char *p = buf; + int i; + + for (i = 0; i < round_down(bytes, sizeof(u32)); i += sizeof(u32)) { + u32 random = prandom_u32_state(state); + int j; + + for (j = 0; j < sizeof(u32); j++) { + p[i + j] = random; + random >>= BITS_PER_BYTE; + } + } + if (i < bytes) { + u32 random = prandom_u32_state(state); + + for (; i < bytes; i++) { + p[i] = random; + random >>= BITS_PER_BYTE; + } + } +} +EXPORT_SYMBOL(prandom_bytes_state); + +/** + * prandom_bytes - get the requested number of pseudo-random bytes + * @buf: where to copy the pseudo-random bytes to + * @bytes: the requested number of bytes + */ +void prandom_bytes(void *buf, int bytes) +{ + struct rnd_state *state = &get_cpu_var(net_rand_state); + + prandom_bytes_state(state, buf, bytes); + put_cpu_var(state); +} +EXPORT_SYMBOL(prandom_bytes); + /** * prandom_seed - add entropy to pseudo random number generator * @seed: seed value -- cgit v1.2.3