From efb5751fec2aad9cfa98922b11879f9e4efed59d Mon Sep 17 00:00:00 2001 From: Peter Dettman Date: Thu, 10 Mar 2016 14:05:15 +0700 Subject: Prefer high bits for powers-of-two --- crypto/src/security/SecureRandom.cs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) (limited to 'crypto/src/security') diff --git a/crypto/src/security/SecureRandom.cs b/crypto/src/security/SecureRandom.cs index cb831acc2..bd639a336 100644 --- a/crypto/src/security/SecureRandom.cs +++ b/crypto/src/security/SecureRandom.cs @@ -170,6 +170,7 @@ namespace Org.BouncyCastle.Security public override int Next(int maxValue) { + if (maxValue < 2) { if (maxValue < 0) @@ -178,13 +179,16 @@ namespace Org.BouncyCastle.Security return 0; } + int bits; + // Test whether maxValue is a power of 2 if ((maxValue & (maxValue - 1)) == 0) { - return NextInt() & (maxValue - 1); + bits = NextInt() & int.MaxValue; + return (int)(((long)bits * maxValue) >> 31); } - int bits, result; + int result; do { bits = NextInt() & int.MaxValue; -- cgit 1.4.1