summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authormatthew <>2012-06-24 18:25:12 +0000
committermatthew <>2012-06-24 18:25:12 +0000
commit26f1ea7161535fd185da9771c961054d978da49c (patch)
treeeac1135834e3aeaff5522b5fef7c5aa8eda177e7 /src
parente4f72d62c2695455be7c3b29622722dc4b345426 (diff)
downloadopenbsd-26f1ea7161535fd185da9771c961054d978da49c.tar.gz
openbsd-26f1ea7161535fd185da9771c961054d978da49c.tar.bz2
openbsd-26f1ea7161535fd185da9771c961054d978da49c.zip
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
Diffstat (limited to 'src')
-rw-r--r--src/lib/libc/crypt/arc4random.c15
1 files changed, 3 insertions, 12 deletions
diff --git a/src/lib/libc/crypt/arc4random.c b/src/lib/libc/crypt/arc4random.c
index 43c6fc0435..1697752a1a 100644
--- a/src/lib/libc/crypt/arc4random.c
+++ b/src/lib/libc/crypt/arc4random.c
@@ -1,4 +1,4 @@
1/* $OpenBSD: arc4random.c,v 1.22 2010/12/22 08:23:42 otto Exp $ */ 1/* $OpenBSD: arc4random.c,v 1.23 2012/06/24 18:25:12 matthew Exp $ */
2 2
3/* 3/*
4 * Copyright (c) 1996, David Mazieres <dm@uun.org> 4 * Copyright (c) 1996, David Mazieres <dm@uun.org>
@@ -214,17 +214,8 @@ arc4random_uniform(u_int32_t upper_bound)
214 if (upper_bound < 2) 214 if (upper_bound < 2)
215 return 0; 215 return 0;
216 216
217#if (ULONG_MAX > 0xffffffffUL) 217 /* 2**32 % x == (2**32 - x) % x */
218 min = 0x100000000UL % upper_bound; 218 min = -upper_bound % upper_bound;
219#else
220 /* Calculate (2**32 % upper_bound) avoiding 64-bit math */
221 if (upper_bound > 0x80000000)
222 min = 1 + ~upper_bound; /* 2**32 - upper_bound */
223 else {
224 /* (2**32 - (x * 2)) % x == 2**32 % x when x <= 2**31 */
225 min = ((0xffffffff - (upper_bound * 2)) + 1) % upper_bound;
226 }
227#endif
228 219
229 /* 220 /*
230 * This could theoretically loop forever but each retry has 221 * This could theoretically loop forever but each retry has