diff options
author | Peter Dettman <peter.dettman@bouncycastle.org> | 2016-03-10 14:05:15 +0700 |
---|---|---|
committer | Peter Dettman <peter.dettman@bouncycastle.org> | 2016-03-10 14:05:15 +0700 |
commit | efb5751fec2aad9cfa98922b11879f9e4efed59d (patch) | |
tree | ab905a1eb75f1fe35e18648c7f7be9b0563f4997 /crypto/src/security/SecureRandom.cs | |
parent | Implement unique name_type restriction from RFC 6066 (diff) | |
download | BouncyCastle.NET-ed25519-efb5751fec2aad9cfa98922b11879f9e4efed59d.tar.xz |
Prefer high bits for powers-of-two
Diffstat (limited to 'crypto/src/security/SecureRandom.cs')
-rw-r--r-- | crypto/src/security/SecureRandom.cs | 8 |
1 files changed, 6 insertions, 2 deletions
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; |