diff --git a/crypto/src/security/SecureRandom.cs b/crypto/src/security/SecureRandom.cs
index 5bad57a14..cb831acc2 100644
--- a/crypto/src/security/SecureRandom.cs
+++ b/crypto/src/security/SecureRandom.cs
@@ -68,11 +68,18 @@ namespace Org.BouncyCastle.Security
if (autoSeed)
{
prng.AddSeedMaterial(NextCounterValue());
- prng.AddSeedMaterial(GetSeed(digest.GetDigestSize()));
+ prng.AddSeedMaterial(GetNextBytes(Master, digest.GetDigestSize()));
}
return prng;
}
+ public static byte[] GetNextBytes(SecureRandom secureRandom, int length)
+ {
+ byte[] result = new byte[length];
+ secureRandom.NextBytes(result);
+ return result;
+ }
+
/// <summary>
/// Create and auto-seed an instance based on the given algorithm.
/// </summary>
@@ -91,7 +98,7 @@ namespace Org.BouncyCastle.Security
public static SecureRandom GetInstance(string algorithm, bool autoSeed)
{
string upper = Platform.ToUpperInvariant(algorithm);
- if (upper.EndsWith("PRNG"))
+ if (Platform.EndsWith(upper, "PRNG"))
{
string digestName = upper.Substring(0, upper.Length - "PRNG".Length);
DigestRandomGenerator prng = CreatePrng(digestName, autoSeed);
@@ -104,12 +111,10 @@ namespace Org.BouncyCastle.Security
throw new ArgumentException("Unrecognised PRNG algorithm: " + algorithm, "algorithm");
}
+ [Obsolete("Call GenerateSeed() on a SecureRandom instance instead")]
public static byte[] GetSeed(int length)
{
-#if NETCF_1_0
- lock (master)
-#endif
- return Master.GenerateSeed(length);
+ return GetNextBytes(Master, length);
}
protected readonly IRandomGenerator generator;
@@ -145,11 +150,7 @@ namespace Org.BouncyCastle.Security
public virtual byte[] GenerateSeed(int length)
{
- SetSeed(DateTime.Now.Ticks);
-
- byte[] rv = new byte[length];
- NextBytes(rv);
- return rv;
+ return GetNextBytes(Master, length);
}
public virtual void SetSeed(byte[] seed)
@@ -164,13 +165,7 @@ namespace Org.BouncyCastle.Security
public override int Next()
{
- for (;;)
- {
- int i = NextInt() & int.MaxValue;
-
- if (i != int.MaxValue)
- return i;
- }
+ return NextInt() & int.MaxValue;
}
public override int Next(int maxValue)
@@ -184,11 +179,9 @@ namespace Org.BouncyCastle.Security
}
// Test whether maxValue is a power of 2
- if ((maxValue & -maxValue) == maxValue)
+ if ((maxValue & (maxValue - 1)) == 0)
{
- int val = NextInt() & int.MaxValue;
- long lr = ((long) maxValue * (long) val) >> 31;
- return (int) lr;
+ return NextInt() & (maxValue - 1);
}
int bits, result;
@@ -244,16 +237,17 @@ namespace Org.BouncyCastle.Security
public virtual int NextInt()
{
- byte[] intBytes = new byte[4];
- NextBytes(intBytes);
-
- int result = 0;
- for (int i = 0; i < 4; i++)
- {
- result = (result << 8) + (intBytes[i] & 0xff);
- }
-
- return result;
+ byte[] bytes = new byte[4];
+ NextBytes(bytes);
+
+ uint result = bytes[0];
+ result <<= 8;
+ result |= bytes[1];
+ result <<= 8;
+ result |= bytes[2];
+ result <<= 8;
+ result |= bytes[3];
+ return (int)result;
}
public virtual long NextLong()
|