xref: /freebsd/contrib/unbound/compat/arc4random_uniform.c (revision 5ca8e32633c4ffbbcd6762e5888b6a4ba0708c6c)
1 /*      $OpenBSD: arc4random_uniform.c,v 1.1 2014/07/12 13:24:54 deraadt Exp $  */
2 
3 /*
4  * Copyright (c) 2008, Damien Miller <djm@openbsd.org>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 
19 #include "config.h"
20 #include <sys/types.h>
21 #include <stdlib.h>
22 
23 /*
24  * Calculate a uniformly distributed random number less than upper_bound
25  * avoiding "modulo bias".
26  *
27  * Uniformity is achieved by generating new random numbers until the one
28  * returned is outside the range [0, 2**32 % upper_bound).  This
29  * guarantees the selected random number will be inside
30  * [2**32 % upper_bound, 2**32) which maps back to [0, upper_bound)
31  * after reduction modulo upper_bound.
32  */
33 uint32_t
34 arc4random_uniform(uint32_t upper_bound)
35 {
36 	uint32_t r, min;
37 
38 	if (upper_bound < 2)
39 		return 0;
40 
41 	/* 2**32 % x == (2**32 - x) % x */
42 	min = -upper_bound % upper_bound;
43 
44 	/*
45 	 * This could theoretically loop forever but each retry has
46 	 * p > 0.5 (worst case, usually far better) of selecting a
47 	 * number inside the range we need, so it should rarely need
48 	 * to re-roll.
49 	 */
50 	for (;;) {
51 		r = arc4random();
52 		if (r >= min)
53 			break;
54 	}
55 
56 	return r % upper_bound;
57 }
58