Browse Source

Revert changes in BigInteger.Random(int bitLength) from commit 1b881f5df30491c7a6e1fb5957d3c0fe25170805.
Fixes issue #147.

Gert Driesen 8 năm trước cách đây
mục cha
commit
3f28d8c175

+ 14 - 0
src/Renci.SshNet.Tests/Classes/Common/BigIntegerTest.cs

@@ -1651,6 +1651,20 @@ namespace Renci.SshNet.Tests.Classes.Common
             Assert.AreEqual(0, zero.Sign);
         }
 
+        [TestMethod]
+        public void Random()
+        {
+            var max = "26432534714839143538998938508341375449389492936207135611931371046236385860280414659368073862189301615603000443463893527273703804361856647266218472759410964268979057798543462774631912259980510080575520846081682603934587649566608158932346151315049355432937004801361578344502537300865702429436253728164365180058583916866804254965536833106467354901266304654706123552932560896874808786957654734387252964281680963136344135750381838556467139236094522411774117748615141352874979928570068255439327082539676660277104989857941859821396157749462154431239343148671646397611770487668571604363151098131876313773395912355145689712506";
+            BigInteger maxBigInt;
+            Assert.IsTrue(BigInteger.TryParse(max, NumberStyles.Number, NumberFormatInfo.CurrentInfo, out maxBigInt));
+
+            var random = BigInteger.One;
+            while (random <= BigInteger.One || random >= maxBigInt)
+            {
+                random = BigInteger.Random(2048);
+            }
+        }
+
         [TestMethod]
         public void TestClientExhcangeGenerationItem130()
         {

+ 4 - 24
src/Renci.SshNet/Common/BigInteger.cs

@@ -171,30 +171,10 @@ namespace Renci.SshNet.Common
         /// <returns>A random number of the specified length.</returns>
         public static BigInteger Random(int bitLength)
         {
-            int dwords = bitLength >> 5;
-            int remBits = bitLength & 0x1F;
-
-            if (remBits != 0)
-                dwords++;
-
-            BigInteger ret = new BigInteger(1, new uint[(uint)dwords + 1]);
-            byte[] random = new byte[dwords << 2];
-
-            CryptoAbstraction.GenerateRandom(random);
-            Buffer.BlockCopy(random, 0, ret._data, 0, (int)dwords << 2);
-
-            if (remBits != 0)
-            {
-                uint mask = (uint)(0x01 << (remBits - 1));
-                ret._data[dwords - 1] |= mask;
-
-                mask = (uint)(0xFFFFFFFF >> (32 - remBits));
-                ret._data[dwords - 1] &= mask;
-            }
-            else
-                ret._data[dwords - 1] |= 0x80000000;
-
-            return ret;
+            var bytesArray = new byte[bitLength / 8 + (((bitLength % 8) > 0) ? 1 : 0)];
+            CryptoAbstraction.GenerateRandom(bytesArray);
+            bytesArray[bytesArray.Length - 1] = (byte) (bytesArray[bytesArray.Length - 1] & 0x7F);   //  Ensure not a negative value 
+            return new BigInteger(bytesArray);
         }
 
         #endregion SSH.NET additions