81 lines
2.6 KiB
Objective-C
81 lines
2.6 KiB
Objective-C
/*
|
|
* Copyright (c) 1996, David Mazieres <dm@uun.org>
|
|
* Copyright (c) 2008, Damien Miller <djm@openbsd.org>
|
|
*
|
|
* Permission to use, copy, modify, and distribute this software for any
|
|
* purpose with or without fee is hereby granted, provided that the above
|
|
* copyright notice and this permission notice appear in all copies.
|
|
*
|
|
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
|
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
|
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
|
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
|
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
|
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
|
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
|
*/
|
|
|
|
/*
|
|
* Arc4 random number generator for OpenBSD.
|
|
*
|
|
* This code is derived from section 17.1 of Applied Cryptography,
|
|
* second edition, which describes a stream cipher allegedly
|
|
* compatible with RSA Labs "RC4" cipher (the actual description of
|
|
* which is a trade secret). The same algorithm is used as a stream
|
|
* cipher called "arcfour" in Tatu Ylonen's ssh package.
|
|
*
|
|
* RC4 is a registered trademark of RSA Laboratories.
|
|
*/
|
|
|
|
#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || \
|
|
defined(__APPLE__)
|
|
# include <stdlib.h>
|
|
#else
|
|
# include <bsd/stdlib.h>
|
|
#endif
|
|
#include <stdint.h>
|
|
|
|
/*
|
|
* Calculate a uniformly distributed random number less than upper_bound
|
|
* avoiding "modulo bias".
|
|
*
|
|
* Uniformity is achieved by generating new random numbers until the one
|
|
* returned is outside the range [0, 2**32 % upper_bound). This
|
|
* guarantees the selected random number will be inside
|
|
* [2**32 % upper_bound, 2**32) which maps back to [0, upper_bound)
|
|
* after reduction modulo upper_bound.
|
|
*/
|
|
uint32_t
|
|
arc4random_uniform(uint32_t upper_bound)
|
|
{
|
|
uint32_t r, min;
|
|
|
|
if (upper_bound < 2)
|
|
return 0;
|
|
|
|
#if (ULONG_MAX > 0xffffffffUL)
|
|
min = 0x100000000UL % upper_bound;
|
|
#else
|
|
/* Calculate (2**32 % upper_bound) avoiding 64-bit math */
|
|
if (upper_bound > 0x80000000)
|
|
min = 1 + ~upper_bound; /* 2**32 - upper_bound */
|
|
else {
|
|
/* (2**32 - (x * 2)) % x == 2**32 % x when x <= 2**31 */
|
|
min = ((0xffffffff - (upper_bound * 2)) + 1) % upper_bound;
|
|
}
|
|
#endif
|
|
|
|
/*
|
|
* This could theoretically loop forever but each retry has
|
|
* p > 0.5 (worst case, usually far better) of selecting a
|
|
* number inside the range we need, so it should rarely need
|
|
* to re-roll.
|
|
*/
|
|
for (;;) {
|
|
r = arc4random();
|
|
if (r >= min)
|
|
break;
|
|
}
|
|
|
|
return r % upper_bound;
|
|
}
|