From 5ba17ff2cce3d8a59aed2c0cc879c2c95e09e084 Mon Sep 17 00:00:00 2001 From: matthew <> Date: Sun, 24 Jun 2012 18:25:12 +0000 Subject: [PATCH] Change arc4random_uniform() to calculate ``2**32 % upper_bound'' as ``-upper_bound % upper_bound''. Simplifies the code and makes it the same on both ILP32 and LP64 architectures, and also slightly faster on LP64 architectures by using a 32-bit remainder instead of a 64-bit remainder. Pointed out by Jorden Verwer on tech@ ok deraadt; no objections from djm or otto --- src/lib/libc/crypt/arc4random.c | 15 +++------------ 1 file changed, 3 insertions(+), 12 deletions(-) diff --git a/src/lib/libc/crypt/arc4random.c b/src/lib/libc/crypt/arc4random.c index 43c6fc04..1697752a 100644 --- a/src/lib/libc/crypt/arc4random.c +++ b/src/lib/libc/crypt/arc4random.c @@ -1,4 +1,4 @@ -/* $OpenBSD: arc4random.c,v 1.22 2010/12/22 08:23:42 otto Exp $ */ +/* $OpenBSD: arc4random.c,v 1.23 2012/06/24 18:25:12 matthew Exp $ */ /* * Copyright (c) 1996, David Mazieres @@ -214,17 +214,8 @@ arc4random_uniform(u_int32_t upper_bound) 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 + /* 2**32 % x == (2**32 - x) % x */ + min = -upper_bound % upper_bound; /* * This could theoretically loop forever but each retry has