1247738Sbapt/*      $OpenBSD: arc4random_uniform.c,v 1.1 2014/07/12 13:24:54 deraadt Exp $  */
2247738Sbapt
3247738Sbapt/*
4247738Sbapt * Copyright (c) 2008, Damien Miller <djm@openbsd.org>
5247738Sbapt *
6247738Sbapt * Permission to use, copy, modify, and distribute this software for any
7247738Sbapt * purpose with or without fee is hereby granted, provided that the above
8247738Sbapt * copyright notice and this permission notice appear in all copies.
9247738Sbapt *
10247738Sbapt * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11247738Sbapt * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12247738Sbapt * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13247738Sbapt * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14247738Sbapt * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15247738Sbapt * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16247738Sbapt * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17247738Sbapt */
18247738Sbapt
19247738Sbapt#include "config.h"
20247738Sbapt#include <sys/types.h>
21247738Sbapt#include <stdlib.h>
22247738Sbapt
23247738Sbapt/*
24247738Sbapt * Calculate a uniformly distributed random number less than upper_bound
25247738Sbapt * avoiding "modulo bias".
26247738Sbapt *
27247738Sbapt * Uniformity is achieved by generating new random numbers until the one
28247738Sbapt * returned is outside the range [0, 2**32 % upper_bound).  This
29247738Sbapt * guarantees the selected random number will be inside
30247738Sbapt * [2**32 % upper_bound, 2**32) which maps back to [0, upper_bound)
31247738Sbapt * after reduction modulo upper_bound.
32247738Sbapt */
33247738Sbaptuint32_t
34247738Sbaptarc4random_uniform(uint32_t upper_bound)
35247738Sbapt{
36247738Sbapt	uint32_t r, min;
37247738Sbapt
38247738Sbapt	if (upper_bound < 2)
39247738Sbapt		return 0;
40247738Sbapt
41247738Sbapt	/* 2**32 % x == (2**32 - x) % x */
42247738Sbapt	min = -upper_bound % upper_bound;
43247738Sbapt
44247738Sbapt	/*
45247738Sbapt	 * This could theoretically loop forever but each retry has
46247738Sbapt	 * p > 0.5 (worst case, usually far better) of selecting a
47247738Sbapt	 * number inside the range we need, so it should rarely need
48247738Sbapt	 * to re-roll.
49247738Sbapt	 */
50247738Sbapt	for (;;) {
51247738Sbapt		r = arc4random();
52247738Sbapt		if (r >= min)
53247738Sbapt			break;
54247738Sbapt	}
55247738Sbapt
56247738Sbapt	return r % upper_bound;
57247738Sbapt}
58247738Sbapt