summary refs log tree commit diff
path: root/crypto/test
diff options
context:
space:
mode:
authorPeter Dettman <peter.dettman@bouncycastle.org>2020-06-21 17:09:46 +0700
committerPeter Dettman <peter.dettman@bouncycastle.org>2020-06-21 17:09:46 +0700
commit6e3772756b4375842f7eea6c36880614c5528719 (patch)
tree50b9a1d54dacc5069e194835afd198d1a11fdc90 /crypto/test
parentDon't use 'var' keyword (diff)
downloadBouncyCastle.NET-ed25519-6e3772756b4375842f7eea6c36880614c5528719.tar.xz
Fix range and bias of NextDouble
- see https://github.com/bcgit/bc-csharp/issues/253
Diffstat (limited to 'crypto/test')
-rw-r--r--crypto/test/src/security/test/SecureRandomTest.cs48
1 files changed, 48 insertions, 0 deletions
diff --git a/crypto/test/src/security/test/SecureRandomTest.cs b/crypto/test/src/security/test/SecureRandomTest.cs
index 98bf75508..a474b5339 100644
--- a/crypto/test/src/security/test/SecureRandomTest.cs
+++ b/crypto/test/src/security/test/SecureRandomTest.cs
@@ -10,6 +10,7 @@ using Org.BouncyCastle.Crypto.Macs;
 using Org.BouncyCastle.Crypto.Prng;
 using Org.BouncyCastle.Crypto.Parameters;
 using Org.BouncyCastle.Utilities;
+using Org.BouncyCastle.Utilities.Test;
 
 namespace Org.BouncyCastle.Security.Tests
 {
@@ -36,6 +37,18 @@ namespace Org.BouncyCastle.Security.Tests
         }
 
         [Test]
+        public void TestNextDouble()
+        {
+            double min = new SecureRandom(new FixedRandomGenerator(0x00)).NextDouble();
+            Assert.GreaterOrEqual(min, 0.0);
+            Assert.Less(min, 1.0);
+
+            double max = new SecureRandom(new FixedRandomGenerator(0xFF)).NextDouble();
+            Assert.GreaterOrEqual(max, 0.0);
+            Assert.Less(max, 1.0);
+        }
+
+        [Test]
         public void TestSha1Prng()
         {
             SecureRandom random = SecureRandom.GetInstance("SHA1PRNG");
@@ -198,5 +211,40 @@ namespace Org.BouncyCastle.Security.Tests
 
             return chi2;
         }
+
+        private abstract class TestRandomGenerator
+            : IRandomGenerator
+        {
+            public virtual void AddSeedMaterial(byte[] seed)
+            {
+            }
+
+            public virtual void AddSeedMaterial(long seed)
+            {
+            }
+
+            public virtual void NextBytes(byte[] bytes)
+            {
+                NextBytes(bytes, 0, bytes.Length);
+            }
+
+            public abstract void NextBytes(byte[] bytes, int start, int len);
+        }
+
+        private sealed class FixedRandomGenerator
+            : TestRandomGenerator
+        {
+            private readonly byte b;
+
+            internal FixedRandomGenerator(byte b)
+            {
+                this.b = b;
+            }
+
+            public override void NextBytes(byte[] bytes, int start, int len)
+            {
+                Arrays.Fill(bytes, start, start + len, b);
+            }
+        }
     }
 }