示例#1
0
        /// <summary>
        /// Adds another coefficient thereby increasing the degree by one.
        /// </summary>
        /// <param name="coefficient">Coefficient to add.</param>
        public void AddCoefficient(BigInt coefficient)
        {
            if (coefficient == null)
            throw new ArgumentNullException("coefficient");

              this.coefficients.Add(coefficient);
        }
 public void Multiply_BigBySmall()
 {
     var big = new BigInt("2892858921897322738439223225");
     int small = 93743224;
     Assert.AreEqual("271185921915819230469801513167177400",
                     (big * small).ToString());
 }
示例#3
0
        public void Add_TwoZeroNumbers_ExpectEqualToZero()
        {
            var zero1 = new BigInt();
            var zero2 = new BigInt();

            var sum = BigInt.Add(zero1, zero2);

            Assert.AreEqual("0", sum.ToString());
        }
示例#4
0
文件: Share.cs 项目: dbrgn/pi-vote
        public Share(BigInt value, int sourceAuthorityIndex, int destinationAuthorityIndex)
        {
            if (value == null)
            throw new ArgumentNullException("value");

              Value = value;
              SourceAuthorityIndex = sourceAuthorityIndex;
              DestinationAuthorityIndex = destinationAuthorityIndex;
        }
示例#5
0
 public static BigInt factorial(BigInt fac)
 {
     // Problem 34 - Factorial done correctly
     BigInt result = 1;
     for (BigInt i = 1; i <= fac; i++)
     {
         result *= i;
     }
     return result;
 }
示例#6
0
文件: Form1.cs 项目: dawndiy/BigInt
 //求大数A的绝对值
 private static BigInt abs(BigInt A)
 {
     if (A.count == 0)
     {
         return new BigInt(0);
     }
     BigInt A0 = new BigInt(A.count);
     A.part.CopyTo(A0.part, 0);
     return A0;
 }
示例#7
0
 public static BigInt factoral(BigInt fac)
 {
     // Problem 20
     // Note: This is NOT a factorial done correctly...
     BigInt result = 1;
     for (BigInt i = 1; i < fac; i++)
     {
         result *= i;
     }
     return result;
 }
示例#8
0
        /// <summary>
        /// Creates a new partial decipher.
        /// </summary>
        /// <param name="groupIndex">Index of the partial decipher group. Equals index of authority not in this group.</param>
        /// <param name="questionIndex">Index of question in the voting.</param>
        /// <param name="optionIndex">Index of the option in the question.</param>
        /// <param name="value">Value of the partial decipher</param>
        public PartialDecipher(int authorityIndex, int groupIndex, int questionIndex, int optionIndex, BigInt value)
        {
            if (value == null)
            throw new ArgumentNullException("value");

              AuthorityIndex = authorityIndex;
              QuestionIndex = questionIndex;
              GroupIndex = groupIndex;
              OptionIndex = optionIndex;
              Value = value;
        }
示例#9
0
        public Authority(DeserializeContext context, BaseParameters parameters)
        {
            Index = context.ReadInt32();
              this.polynomial = context.ReadObject<Polynomial>();

              if (!context.ReadBoolean())
              {
            this.secretKeyPart = context.ReadBigInt();
              }

              this.parameters = parameters;
        }
示例#10
0
 public static BigInt FactorialSumOfDigits(BigInt fac)
 {
     String s = fac.ToString();
     BigInt sum = 0;
     for (int i = 0; i < s.Length; i++)
     {
         String ss = s.Substring(i, 1);
         sum += factorial(BigInt.Parse(s.Substring(i, 1)));
         // s.Substring((int)i, 1)
     }
     return sum;
 }
示例#11
0
 static void Main(string[] args)
 {
     BigInt b = new BigInt();
     b = ProjectEuler.ProjectEuler.power(2, 1000);
     char[] array = b.ToString().ToCharArray();
     b = 0;
     for (int i = 0; i < array.Length; i++)
     {
         b += int.Parse(array[i].ToString());
     }
     Console.WriteLine(b.ToString());
 }
示例#12
0
文件: Form1.cs 项目: dawndiy/BigInt
 //这是计算大数乘大数的子程序
 /* 错位相加,结果非负;错位方法:A左移9k位,要求(A的位数+9k)不少于B的位数 */
 private static BigInt add(BigInt A, BigInt B, ushort k)
 {
     if (A.count == 0)
     { return abs(B); }
     if (k == 0)
     { return add(A, B); }
     BigInt A0 = new BigInt((ushort)(A.count + 9 * k));
     A.part.CopyTo(A0.part, k);
     if (B.count <= 9 * k)
     {
         if (B.count != 0)
         {
             B.part.CopyTo(A0.part, 0);
         }
         return A0;
     }
     Array.Copy(B.part, 0, A0.part, 0, k);
     byte c = 0;   // c为进位值
     byte a = (byte)A0.part[A0.part.Length - 1].ToString().Length;
     int temp;
     for (ushort i = k; i < B.part.Length; i++)
     {
         A0.part[i] += B.part[i] + c;
         c = (byte)Math.DivRem((int)A0.part[i], 1000000000, out temp);
         A0.part[i] = (uint)temp;
     }
     if (c == 0)
     {
         if ((A0.part.Length == B.part.Length) && (A0.part[A0.part.Length - 1].ToString().Length > a))
         {
             A0.count++;
         }
         return A0;
     }
     for (ushort i = (ushort)B.part.Length; i < A0.part.Length; i++)
     {
         A0.part[i] += c;
         c = (byte)Math.DivRem((int)A0.part[i], 1000000000, out temp);
         if (c == 0) { break; }
         A0.part[i] = (uint)temp;
     }
     if (c == 0)
     {
         if (A0.part[A0.part.Length - 1].ToString().Length > a)
         { A0.count++; }
         return A0;
     }
     A0.count = (ushort)(9 * A0.part.Length + 1);
     Array.Resize(ref A0.part, A0.part.Length + 1);
     A0.part[A0.part.Length - 1] = 1;
     return A0;
 }
示例#13
0
        public void Add_ZeroAndPositive_ExpectEqualToPositive()
        {
            var a = 829499221;

            var zero = new BigInt();
            var positive = new BigInt(a);

            var sum = BigInt.Add(zero, positive);
            Assert.AreEqual(a.ToString(), sum.ToString());

            sum = BigInt.Add(positive, zero);
            Assert.AreEqual(a.ToString(), sum.ToString());
        }
示例#14
0
 public static BigInt FibIterative(BigInt num)
 {
     BigInt a = 0;
     BigInt b = 1;
     BigInt c = 0;
     if (num < 3) { return 1; }
     for (BigInt i = 0; i < num; i++)
     {
         c = a;
         a = b;
         b = c + b;
     }
     return a;
 }
示例#15
0
        public static BigInt GCD(BigInt a, BigInt b)
        {
            while (a != 0 && b != 0)
            {
                if (a > b)
                    a %= b;
                else
                    b %= a;
            }

            if (a == 0)
                return b;
            else
                return a;
        }
示例#16
0
        public void Add_TwoPositiveResultSameLength_ExpectReturnSum()
        {
            var a = 12345;
            var b = 321;

            var expectedResult = 12666;

            var positive1 = new BigInt(a);
            var positive2 = new BigInt(b);

            var sum = BigInt.Add(positive1, positive2);
            Assert.AreEqual(expectedResult.ToString(), sum.ToString());

            sum = BigInt.Add(positive2, positive1);
            Assert.AreEqual(expectedResult.ToString(), sum.ToString());
        }
示例#17
0
        public static BigInt operator +(BigInt i1, BigInt i2)
        {
            int length = Math.Max(i1.Digits.Count, i2.Digits.Count);
            BigInt result = new BigInt();
            result.Digits = new List<int>(length+1);

            int carry = 0;
            for (int i = 0; i < length; i++)
            {
                var tmp =  (i1.Digits.Count > i ? i1.Digits[i] : 0) + (i2.Digits.Count > i ? i2.Digits[i] : 0) + carry;
                result.Digits.Add(tmp % 10);
                carry = tmp > 9 ? 1 : 0;
            }
            if (carry > 0)
                result.Digits.Add(carry);
            return result;
        }
示例#18
0
        public void Add_TwoPositiveResultIsLonger_ExpectReturnSum()
        {
            var a = 999;
            var b = 111;

            var expectedResult = 1110;

            var positive1 = new BigInt(a);
            var positive2 = new BigInt(b);

            var sum = BigInt.Add(positive1, positive2);
            Assert.AreEqual(expectedResult.ToString(), sum.ToString());

            sum = BigInt.Add(positive2, positive1);
            Assert.AreEqual(expectedResult.ToString(), sum.ToString());

            sum = positive1 + positive2;
            Assert.AreEqual(expectedResult.ToString(), sum.ToString());
        }
示例#19
0
        public static BigInt Fib(BigInt num)
        {
            // Why the static table for some numbers?  Speed!
            if (num < 2) { return num; }
            if (num == 10) { return 55; }
            if (num == 20) { return 6765; }
            if (num == 21) { return 10946; }
            if (num == 40) { return 102334155; }
            if (num == 41) { return 165580141; }
            if (num == 50) { return 12586269025; }
            if (num == 70) { return 190392490709135; }
            if (num == 71) { return 308061521170129; }
            if (num == 80) { return 23416728348467685; }
            if (num == 90) { return 2880067194370816120; }
            if (num == 91) { return 4660046610375530309; }

            else
            {
                return Fib(num - 1) + Fib(num - 2);
            }
        }
示例#20
0
文件: Form1.cs 项目: dawndiy/BigInt
 /* 绝对值相加,结果非负,要求A的位数不少于B的位数 */
 private static BigInt add(BigInt A, BigInt B)
 {
     if (B.count == 0)
     { return abs(A); }
     BigInt A0 = abs(A);
     byte c = 0;   // c为进位值
     byte a = (byte)A0.part[A0.part.Length - 1].ToString().Length;
     int temp;
     for (ushort i = 0; i < B.part.Length; i++)
     {
         A0.part[i] += B.part[i] + c;
         c = (byte)Math.DivRem((int)A0.part[i], 1000000000, out temp);
         A0.part[i] = (uint)temp;
     }
     if (c == 0)
     {
         if ((A0.part.Length == B.part.Length) && (A0.part[A0.part.Length - 1].ToString().Length > a))
         {
             A0.count++;
         }
         return A0;
     }
     for (ushort i = (ushort)B.part.Length; i < A0.part.Length; i++)
     {
         A0.part[i] += c;
         c = (byte)Math.DivRem((int)A0.part[i], 1000000000, out temp);
         if (c == 0) { break; }
         A0.part[i] = (uint)temp;
     }
     if (c == 0)
     {
         if (A0.part[A0.part.Length - 1].ToString().Length > a)
         { A0.count++; }
         return A0;
     }
     A0.count = (ushort)(9 * A0.part.Length + 1);
     Array.Resize(ref A0.part, A0.part.Length + 1);
     A0.part[A0.part.Length - 1] = 1;
     return A0;
 }
    public static BigInt operator +(BigInt lhs, BigInt rhs)
    {
        int newSize = lhs.size > rhs.size ? lhs.size : rhs.size;
        BigInt sum = new BigInt();
        sum.size = newSize;
        for (int i = 0; i < newSize; i++)
        {
            sum.number[i] += (byte)(lhs[i] + rhs[i]);
            if (sum.number[i] > 9)
            {
                sum.number[i + 1]++;
                sum.number[i] %= 10;
                if (i == newSize - 2)
                {
                    sum.size++;
                    newSize++;
                }
            }
        }

        return sum;
    }
示例#22
0
        internal Projective EcTwinMult(BigInt d0, Projective S, BigInt d1, Projective T)
        {
            var d = new BigInt[2] {
                d0, d1
            };

            var SpT = EcFullAdd(S, T);
            var SmT = EcFullSub(S, T);

            var m0 = d0.BitCount();
            var m1 = d1.BitCount();
            var m  = Math.Max(m0, m1);

            var c = new int[2][];

            c[0] = new int[6] {
                0, 0, d0.BitAt(m - 1) ? 1 : 0, d0.BitAt(m - 2) ? 1 : 0, d0.BitAt(m - 3) ? 1 : 0, d0.BitAt(m - 4) ? 1 : 0
            };
            c[1] = new int[6] {
                0, 0, d1.BitAt(m - 1) ? 1 : 0, d1.BitAt(m - 2) ? 1 : 0, d1.BitAt(m - 3) ? 1 : 0, d1.BitAt(m - 4) ? 1 : 0
            };

            var R = new Projective()
            {
                x = new BigInt(1, S.x.Length), y = new BigInt(1, S.x.Length), z = new BigInt(0, S.x.Length)
            };

            int[] h = new int[2], u = new int[2];

            for (var k = m; k >= 0; k--)
            {
                for (var i = 0; i <= 1; i++)
                {
                    h[i] = (c[i][1] << 4) + (c[i][2] << 3) + (c[i][3] << 2) + (c[i][4] << 1) + c[i][5];
                    if (c[i][0] == 1)
                    {
                        h[i] = 31 - h[i];
                    }
                }
                for (var i = 0; i <= 1; i++)
                {
                    var t = h[1 - i];
                    int f;
                    if (18 <= t && t < 22)
                    {
                        f = 9;
                    }
                    else if (14 <= t && t < 18)
                    {
                        f = 10;
                    }
                    else if (22 <= t && t < 24)
                    {
                        f = 11;
                    }
                    else if (4 <= t && t < 12)
                    {
                        f = 14;
                    }
                    else
                    {
                        f = 12;
                    }
                    if (h[i] < f)
                    {
                        u[i] = 0;
                    }
                    else
                    {
                        u[i] = (c[i][0] & 1) != 0 ? -1 : 1;
                    }
                }
                for (var i = 0; i < 2; i++)
                {
                    c[i][0] = ((u[i] != 0) ^ (c[i][1] != 0)) ? 1 : 0;
                    c[i][1] = c[i][2];
                    c[i][2] = c[i][3];
                    c[i][3] = c[i][4];
                    c[i][4] = c[i][5];
                    c[i][5] = d[i].BitAt(k - 5) ? 1 : 0;
                }
                R = EcDouble(R);
                if (u[0] == -1)
                {
                    if (u[1] == -1)
                    {
                        R = EcFullSub(R, SpT);
                    }
                    else if (u[1] == 0)
                    {
                        R = EcFullSub(R, S);
                    }
                    else
                    {
                        R = EcFullSub(R, SmT);
                    }
                }
                else if (u[0] == 0)
                {
                    if (u[1] == -1)
                    {
                        R = EcFullSub(R, T);
                    }
                    else if (u[1] == 1)
                    {
                        R = EcFullAdd(R, T);
                    }
                }
                else if (u[0] == 1)
                {
                    if (u[1] == -1)
                    {
                        R = EcFullAdd(R, SmT);
                    }
                    else if (u[1] == 0)
                    {
                        R = EcFullAdd(R, S);
                    }
                    else
                    {
                        R = EcFullAdd(R, SpT);
                    }
                }
            }

            return(R);
        }
示例#23
0
        public static IDataItem FromXElement(XElement element)
        {
            if (element == null)
            {
                return(new NullDataItem());
            }
            var type = element.Attribute("type").Value;
            var text = element.Value;

            switch (type)
            {
            case "int32":
                return(new Int32DataItem(Int32.Parse(text)));

            case "uint32":
                return(new UInt32DataItem(UInt32.Parse(text)));

            case "int64":
                return(new Int64DataItem(Int64.Parse(text)));

            case "uint64":
                return(new UInt64DataItem(UInt64.Parse(text)));

            case "decimal":
                return(new DecimalDataItem(decimal.Parse(text)));

            case "double":
                return(new DoubleDataItem(double.Parse(text)));

            case "bigint":
            {
                var bytes = text.Split(',').Select(x => byte.Parse(x, NumberStyles.HexNumber)).ToArray();
                var p     = BigInt.FromByteArray(bytes);
                return(new BigIntDataItem(p));
            }

            case "ubigint":
            {
                var bytes = text.Split(',').Select(x => byte.Parse(x, NumberStyles.HexNumber)).ToArray();
                var p     = UBigInt.FromByteArray(bytes);
                return(new UBigIntDataItem(p));
            }

            case "rational":
            {
                var bytes = text.Split(',').Select(x => byte.Parse(x, NumberStyles.HexNumber)).ToArray();
                var p     = Rational.FromByteArray(bytes);
                return(new RationalDataItem(p));
            }

            case "string":
                return(new XStringDataItem(text));

            case "numberformatinfo":
            {
                var dic = text.Split(':')
                          .Where(line => line != "")
                          .Select(line => line.Split('='))
                          .Select(columns =>
                    {
                        if (columns.Length != 2)
                        {
                            throw new ApplicationException();
                        }
                        var key   = columns[0];
                        var value = columns[1].Replace("&#58;", ":").Replace("&#61;", "=").Replace("&amp;", "&");
                        return(new { key, value });
                    })
                          .ToDictionary(item => item.key, item => item.value);
                var culture = dic.ContainsKey("CultureName") ? CultureInfo.CreateSpecificCulture(dic["CultureName"]) : CultureInfo.InvariantCulture;
                foreach (var key_value in dic)
                {
                    switch (key_value.Key)
                    {
                    case "CurrencyDecimalDigits":
                        culture.NumberFormat.CurrencyDecimalDigits = int.Parse(key_value.Value);
                        break;

                    case "CurrencyDecimalSeparator":
                        culture.NumberFormat.CurrencyDecimalSeparator = key_value.Value;
                        break;

                    case "CurrencyGroupSeparator":
                        culture.NumberFormat.CurrencyGroupSeparator = key_value.Value;
                        break;

                    case "CurrencyGroupSizes":
                        culture.NumberFormat.CurrencyGroupSizes = key_value.Value.Select(c => c - '0').ToArray();
                        break;

                    case "CurrencyNegativePattern":
                        culture.NumberFormat.CurrencyNegativePattern = int.Parse(key_value.Value);
                        break;

                    case "CurrencyPositivePattern":
                        culture.NumberFormat.CurrencyPositivePattern = int.Parse(key_value.Value);
                        break;

                    case "CurrencySymbol":
                        culture.NumberFormat.CurrencySymbol = key_value.Value;
                        break;

                    case "NegativeSign":
                        culture.NumberFormat.NegativeSign = key_value.Value;
                        break;

                    case "NumberDecimalDigits":
                        culture.NumberFormat.NumberDecimalDigits = int.Parse(key_value.Value);
                        break;

                    case "NumberDecimalSeparator":
                        culture.NumberFormat.NumberDecimalSeparator = key_value.Value;
                        break;

                    case "NumberGroupSeparator":
                        culture.NumberFormat.NumberGroupSeparator = key_value.Value;
                        break;

                    case "NumberGroupSizes":
                        culture.NumberFormat.NumberGroupSizes = key_value.Value.Select(c => c - '0').ToArray();
                        break;

                    case "NumberNegativePattern":
                        culture.NumberFormat.NumberNegativePattern = int.Parse(key_value.Value);
                        break;

                    case "PercentDecimalDigits":
                        culture.NumberFormat.PercentDecimalDigits = int.Parse(key_value.Value);
                        break;

                    case "PercentDecimalSeparator":
                        culture.NumberFormat.PercentDecimalSeparator = key_value.Value;
                        break;

                    case "PercentGroupSeparator":
                        culture.NumberFormat.PercentGroupSeparator = key_value.Value;
                        break;

                    case "PercentGroupSizes":
                        culture.NumberFormat.PercentGroupSizes = key_value.Value.Select(c => c - '0').ToArray();
                        break;

                    case "PercentNegativePattern":
                        culture.NumberFormat.PercentNegativePattern = int.Parse(key_value.Value);
                        break;

                    case "PercentPositivePattern":
                        culture.NumberFormat.PercentPositivePattern = int.Parse(key_value.Value);
                        break;

                    case "PercentSymbol":
                        culture.NumberFormat.PercentSymbol = key_value.Value;
                        break;

                    case "PerMilleSymbol":
                        culture.NumberFormat.PerMilleSymbol = key_value.Value;
                        break;

                    case "PositiveSign":
                        culture.NumberFormat.PositiveSign = key_value.Value;
                        break;
                    }
                }
                return(new NumberFormatInfoDataItem(text, culture.NumberFormat));
            }

            case "exception":
                switch (text.ToLower())
                {
                case "overflowexception":
                    return(new ExceptionDataItem(typeof(OverflowException)));

                case "argumentexception":
                    return(new ExceptionDataItem(typeof(ArgumentException)));

                case "argumentnullexception":
                    return(new ExceptionDataItem(typeof(ArgumentNullException)));

                case "formatexception":
                    return(new ExceptionDataItem(typeof(FormatException)));

                case "dividebyzeroexception":
                    return(new ExceptionDataItem(typeof(DivideByZeroException)));

                case "arithmeticexception":
                    return(new ExceptionDataItem(typeof(ArithmeticException)));

                default:
                    throw new ApplicationException();
                }

            default:
                throw new ApplicationException();
            }
        }
示例#24
0
        internal static bool?VerifySignature(byte[] pkParameters, byte[] pkKey, byte[] hash, byte[] signature)
        {
            EllipticCurve curve = GetCurveFromParameters(pkParameters);

            if (curve == null)
            {
                return(null);
            }

            // We must decode the signature from DER format to raw format (to coordinates on the curve)
            int offset = 1;                            // Skip tag 0x30

            Utils.GetASNLength(signature, ref offset); // P521 requires 2 bytes to specify the length
            offset += 1;                               // 0x02
            int len1 = Utils.GetASNLength(signature, ref offset);

            var rBytes = new byte[len1];

            for (var i = 0; i < len1; i++)
            {
                rBytes[i] = signature[offset + len1 - 1 - i];
            }

            offset += len1;
            offset += 1; // 0x02
            int len2 = Utils.GetASNLength(signature, ref offset);

            var sBytes = new byte[len2];

            for (var i = 0; i < len2; i++)
            {
                sBytes[i] = signature[offset + len2 - 1 - i];
            }

            var r = new BigInteger(rBytes);
            var s = new BigInteger(sBytes);

            // Verify that r, s are in [1, q - 1] and Qa lies on the curve

            if (r == 0 || s == 0)
            {
                return(false);
            }
            if (r >= curve.q || s >= curve.q)
            {
                return(false);
            }

            BigInt     Qax = new BigInt(pkKey, 1, curve.curveByteLen), Qay = new BigInt(pkKey, 1 + curve.curveByteLen, curve.curveByteLen);
            BigInteger QaxBi = Qax.ExportToBigInteger(), QayBi = Qay.ExportToBigInteger();

            var pBi = curve.p.ExportToBigInteger();

            if (QaxBi >= pBi || QayBi >= pBi)
            {
                return(false);
            }
            if ((QaxBi * QaxBi * QaxBi - 3 * QaxBi + curve.b + pBi * 3) % pBi != QayBi * QayBi % pBi)
            {
                return(false);
            }

            // Data points are ok, now start verify the signature

            var hashLen = hash.Length;

            byte[] hash2 = null;
            if (hash[0] >= 128)
            {
                hash2 = new byte[hash.Length + 1];
                hash2[hash.Length] = 0;
                for (var i = 0; i < hash.Length; i++)
                {
                    hash2[i] = hash[hash.Length - 1 - i];
                }
            }
            else
            {
                Array.Reverse(hash);
                hash2 = hash;
            }
            var z = new BigInteger(hash2);

            if (hashLen * 8 > curve.curveLen) // Should be compared to order length, but p length is the same for NIST curves
            {
                var excessBits = hashLen * 8 - curve.curveLen;
                z >>= excessBits;
            }
            var w  = BigInteger.ModPow(s, curve.q - 2, curve.q);
            var u1 = z * w % curve.q;
            var u2 = r * w % curve.q;

            var mul = curve.EcTwinMult(new BigInt(u1, (curve.curveByteLen + 3) / 4), new Projective()
            {
                x = curve.xg, y = curve.yg, z = new BigInt(1, (curve.curveByteLen + 3) / 4)
            },
                                       new BigInt(u2, (curve.curveByteLen + 3) / 4), new Projective()
            {
                x = Qax, y = Qay, z = new BigInt(1, (curve.curveByteLen + 3) / 4)
            });
            var res = curve.EcAffinify(mul).x.ExportToBigInteger();

            if (res >= curve.q)
            {
                res -= curve.q;
            }

            bool ok = res == r;

            return(ok);
        }
示例#25
0
 BigInt Replace(BigInt old, BigInt new_)
 {
     old.Clear();
     return(new_);
 }
示例#26
0
        public static void OperatorEqual(string n1, string n2, bool expected)
        {
            var actual = new BigInt(n1) == new BigInt(n2);

            actual.Should().Be(expected);
        }
示例#27
0
        public string Encrypt(int p, int q, string M, int e)
        {
            var    n            = p * q;
            string msgChunckStr = "";
            string result       = "";

            for (int i = 0; i < M.Length; i++)
            {
                msgChunckStr += M[i];
                var msgChunckCheck = BigInt.text(msgChunckStr);
                if (msgChunckCheck >= BigInt.parse(q.ToString()))
                {
                    if (msgChunckStr.Length > 1)
                    {
                        i--;
                        result += RSA_GUI.BigInt.powMod(
                            BigInt.text(msgChunckStr.Substring(0, msgChunckStr.Length - 1)), BigInt.parse(e.ToString()),
                            BigInt.parse(n.ToString())) + " ";
                    }
                    else
                    {
                        result += RSA_GUI.BigInt.powMod(BigInt.text(msgChunckStr.Substring(0, msgChunckStr.Length)),
                                                        BigInt.parse(e.ToString()), BigInt.parse(n.ToString())) + " ";
                    }
                    msgChunckStr = "";
                }
            }
            if (msgChunckStr.Length != 0)
            {
                result += RSA_GUI.BigInt.powMod(BigInt.text(msgChunckStr), BigInt.parse(e.ToString()), BigInt.parse(n.ToString()));
            }
            return(result);
        }
示例#28
0
        public byte[] Decrypt(int p, int q, string C, int e)
        {
            var n    = p * q;
            var phin = (p - 1) * (q - 1);
            var d    = EXmodInv(e, phin);

//            string msgChunckStr = "";
//            for (int i = 0; i < C.Length; i++)
//            {
//                msgChunckStr += C[i];
//                var msgChunckCheck = BigInt.parse(msgChunckStr);
//                if (msgChunckCheck >= BigInt.parse(q.ToString()))
//                {
//                    i--;
//                    result += RSA_GUI.BigInt.powMod(BigInt.text(msgChunckStr.Substring(0, msgChunckStr.Length - 1)), BigInt.parse(d.ToString()), BigInt.parse(n.ToString()));
//                    msgChunckStr = "";
//                }
//            }
//            if (msgChunckStr.Length != 0)
            var result = RSA_GUI.BigInt.powMod(BigInt.parse(C), BigInt.parse(d.ToString()), BigInt.parse(n.ToString()));

            return(result.toArray());
        }
示例#29
0
        public void ProbablePrimeTest()
        {
            BigInt a = BigInt.ProbablePrime(128, new Random());

            Assert.IsTrue(a.IsProbablePrime(10));
        }
示例#30
0
        public static object ToValue(this GraphQLValue source)
        {
            if (source == null)
            {
                return(null);
            }

            switch (source.Kind)
            {
            case ASTNodeKind.NullValue:
            {
                return(null);
            }

            case ASTNodeKind.StringValue:
            {
                var str = source as GraphQLScalarValue;
                Debug.Assert(str != null, nameof(str) + " != null");
                return((string)str.Value);
            }

            case ASTNodeKind.IntValue:
            {
                var str = source as GraphQLScalarValue;

                Debug.Assert(str != null, nameof(str) + " != null");
                if (Int.TryParse(str.Value, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out int intResult))
                {
                    return(intResult);
                }

                // If the value doesn't fit in an integer, revert to using long...
                if (Long.TryParse(str.Value, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out long longResult))
                {
                    return(longResult);
                }

                // If the value doesn't fit in an long, revert to using decimal...
                if (Decimal.TryParse(str.Value, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out decimal decimalResult))
                {
                    return(decimalResult);
                }

                // If the value doesn't fit in an decimal, revert to using BigInteger...
                if (BigInt.TryParse(str.Value, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var bigIntegerResult))
                {
                    return(bigIntegerResult);
                }

                throw new InvalidOperationException($"Invalid number {str.Value}");
            }

            case ASTNodeKind.FloatValue:
            {
                var str = source as GraphQLScalarValue;
                Debug.Assert(str != null, nameof(str) + " != null");

                // the idea is to see if there is a loss of accuracy of value
                // for example, 12.1 or 12.11 is double but 12.10 is decimal
                if (Double.TryParse(
                        str.Value,
                        NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent,
                        CultureInfo.InvariantCulture,
                        out double dbl) == false)
                {
                    dbl = str.Value.Span[0] == '-' ? double.NegativeInfinity : double.PositiveInfinity;
                }

                //it is possible for a FloatValue to overflow a decimal; however, with a double, it just returns Infinity or -Infinity
                if (Decimal.TryParse(
                        str.Value,
                        NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent,
                        CultureInfo.InvariantCulture,
                        out decimal dec))
                {
                    // Cast the decimal to our struct to avoid the decimal.GetBits allocations.
                    var     decBits      = System.Runtime.CompilerServices.Unsafe.As <decimal, DecimalData>(ref dec);
                    decimal temp         = new decimal(dbl);
                    var     dblAsDecBits = System.Runtime.CompilerServices.Unsafe.As <decimal, DecimalData>(ref temp);
                    if (!decBits.Equals(dblAsDecBits))
                    {
                        return(dec);
                    }
                }

                return(dbl);
            }

            case ASTNodeKind.BooleanValue:
            {
                var str = source as GraphQLScalarValue;
                Debug.Assert(str != null, nameof(str) + " != null");
                return((str.Value.Length == 4).Boxed());    /*true.Length=4*/
            }

            case ASTNodeKind.EnumValue:
            {
                var str = source as GraphQLScalarValue;
                Debug.Assert(str != null, nameof(str) + " != null");
                return((string)str.Value);
            }

            case ASTNodeKind.ObjectValue:
            {
                var obj    = source as GraphQLObjectValue;
                var values = new Dictionary <string, object>();

                Debug.Assert(obj != null, nameof(obj) + " != null");
                if (obj.Fields != null)
                {
                    foreach (var f in obj.Fields)
                    {
                        values[(string)f.Name.Value] = ToValue(f.Value);
                    }
                }

                return(values);
            }

            case ASTNodeKind.ListValue:
            {
                var list = source as GraphQLListValue;
                Debug.Assert(list != null, nameof(list) + " != null");

                if (list.Values == null)
                {
                    return(Array.Empty <object>());
                }

                object[] values = list.Values.Select(ToValue).ToArray();
                return(values);
            }

            default:
                throw new InvalidOperationException($"Unsupported value type {source.Kind}");
            }
        }
示例#31
0
 void Assign(ref BigInt variable, BigInt new_)
 {
     variable = Replace(variable, new_);
 }
 public BigIntDataItem(BigInt value)
     : this(string.Join(",", value.ToByteArray().Select(x => x.ToString("x2"))))
 {
 }
示例#33
0
 public Key(BigInt exponent, BigInt module)
 {
     Exponent = exponent;
     Module = module;
 }
示例#34
0
            internal void ModP256()
            {
                var p    = EllipticCurve.P256.p;
                var negP = EllipticCurve.P256.negP;

                var a = _bits;
                var t = new BigInt {
                    _bits = new uint[] { a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7] }
                };
                var s1 = new BigInt {
                    _bits = new uint[] { 0, 0, 0, a[11], a[12], a[13], a[14], a[15] }
                };
                var s2 = new BigInt {
                    _bits = new uint[] { 0, 0, 0, a[12], a[13], a[14], a[15], 0 }
                };
                var s3 = new BigInt {
                    _bits = new uint[] { a[8], a[9], a[10], 0, 0, 0, a[14], a[15] }
                };
                var s4 = new BigInt {
                    _bits = new uint[] { a[9], a[10], a[11], a[13], a[14], a[15], a[13], a[8] }
                };
                var d1 = new BigInt {
                    _bits = new uint[] { a[11], a[12], a[13], 0, 0, 0, a[8], a[10] }
                };
                var d2 = new BigInt {
                    _bits = new uint[] { a[12], a[13], a[14], a[15], 0, 0, a[9], a[11] }
                };
                var d3 = new BigInt {
                    _bits = new uint[] { a[13], a[14], a[15], a[8], a[9], a[10], 0, a[12] }
                };
                var d4 = new BigInt {
                    _bits = new uint[] { a[14], a[15], 0, a[9], a[10], a[11], 0, a[13] }
                };

                bool extraAddD1 = d1 >= p;

                BigInt.TwosComplement(d1._bits, d1._bits);
                BigInt.AddRaw(d1._bits, p._bits, d1._bits);
                if (extraAddD1)
                {
                    BigInt.AddRaw(d1._bits, p._bits, d1._bits);
                }

                bool extraAddD2 = d2 >= p;

                BigInt.TwosComplement(d2._bits, d2._bits);
                BigInt.AddRaw(d2._bits, p._bits, d2._bits);
                if (extraAddD2)
                {
                    BigInt.AddRaw(d2._bits, p._bits, d2._bits);
                }

                BigInt.TwosComplement(d3._bits, d3._bits);
                BigInt.AddRaw(d3._bits, p._bits, d3._bits);
                BigInt.TwosComplement(d4._bits, d4._bits);
                BigInt.AddRaw(d4._bits, p._bits, d4._bits);

                var res   = BigInt.Create(8);
                var toAdd = new BigInt[] { t, s1, s1, s2, s2, s3, s4, d1, d2, d3, d4 };

                foreach (var num in toAdd)
                {
                    var carry = BigInt.AddRaw(num._bits, res._bits, res._bits) == 1;
                    if (carry || res >= p)
                    {
                        BigInt.AddRaw(res._bits, negP._bits, res._bits);
                    }
                }
                foreach (var num in toAdd)
                {
                    num.Clear();
                }
                Clear();
                _bits = res._bits;
            }
示例#35
0
        public void Amount_IsZero_ReturnsRealZeroIfNoCommodity()
        {
            Amount amount = new Amount(BigInt.Parse("0.00005", 2), null);  // Notice that precision less than a value.

            Assert.IsFalse(amount.IsZero);
        }
示例#36
0
 public static void EqualityIgnoreSignTest(string first, string second, int expected)
 {
     Assert.AreEqual(expected, BigInt.Comparison(new BigInt(first), new BigInt(second), true));
 }
示例#37
0
        /// <summary>
        /// Finds both a prime and a larger safe prime.
        /// </summary>
        /// <param name="bitLength">Length in bits for the numbers.</param>
        /// <param name="prime">Returns the prime.</param>
        /// <param name="safePrime">Returns the safe prime.</param>
        public void FindPrimeAndSafePrime(int bitLength, out BigInt prime, out BigInt safePrime)
        {
            DateTime start = DateTime.Now;

              this.bitLength = bitLength;
              this.numberCount = 0;
              this.primeCount = 0;

              List<Thread> threads = new List<Thread>();
              Environment.ProcessorCount.Times(() => threads.Add(new Thread(FindPrime)));
              threads.ForEach(thread => thread.Priority = ThreadPriority.Lowest);
              threads.ForEach(thread => thread.Start());

              while (this.prime == null)
              {
            if (this.feedBack != null)
            {
              this.feedBack(this.numberCount, this.primeCount);
            }

            Thread.Sleep(100);
              }

              threads.ForEach(thread => thread.Join());

              threads = new List<Thread>();
              Environment.ProcessorCount.Times(() => threads.Add(new Thread(FindSafePrime)));
              threads.ForEach(thread => thread.Priority = ThreadPriority.Lowest);
              threads.ForEach(thread => thread.Start());

              while (this.safePrime == null)
              {
            if (this.feedBack != null)
            {
              this.feedBack(this.numberCount, this.primeCount);
            }

            Thread.Sleep(100);
              }

              threads.ForEach(thread => thread.Join());

              prime = this.prime;
              safePrime = this.safePrime;
        }
示例#38
0
            internal void ModP384()
            {
                var p    = EllipticCurve.P384.p;
                var negP = EllipticCurve.P384.negP;

                var a = _bits;
                var t = new BigInt {
                    _bits = new uint[] { a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11] }
                };
                var s1 = new BigInt {
                    _bits = new uint[] { 0, 0, 0, 0, a[21], a[22], a[23], 0, 0, 0, 0, 0 }
                };
                var s2 = new BigInt {
                    _bits = new uint[] { a[12], a[13], a[14], a[15], a[16], a[17], a[18], a[19], a[20], a[21], a[22], a[23] }
                };
                var s3 = new BigInt {
                    _bits = new uint[] { a[21], a[22], a[23], a[12], a[13], a[14], a[15], a[16], a[17], a[18], a[19], a[20] }
                };
                var s4 = new BigInt {
                    _bits = new uint[] { 0, a[23], 0, a[20], a[12], a[13], a[14], a[15], a[16], a[17], a[18], a[19] }
                };
                var s5 = new BigInt {
                    _bits = new uint[] { 0, 0, 0, 0, a[20], a[21], a[22], a[23], 0, 0, 0, 0 }
                };
                var s6 = new BigInt {
                    _bits = new uint[] { a[20], 0, 0, a[21], a[22], a[23], 0, 0, 0, 0, 0, 0 }
                };
                var d1 = new BigInt {
                    _bits = new uint[] { a[23], a[12], a[13], a[14], a[15], a[16], a[17], a[18], a[19], a[20], a[21], a[22] }
                };
                var d2 = new BigInt {
                    _bits = new uint[] { 0, a[20], a[21], a[22], a[23], 0, 0, 0, 0, 0, 0, 0 }
                };
                var d3 = new BigInt {
                    _bits = new uint[] { 0, 0, 0, a[23], a[23], 0, 0, 0, 0, 0, 0, 0 }
                };

                BigInt.TwosComplement(d1._bits, d1._bits);
                BigInt.AddRaw(d1._bits, p._bits, d1._bits);

                BigInt.TwosComplement(d2._bits, d2._bits);
                BigInt.AddRaw(d2._bits, s2._bits, s2._bits);

                BigInt.TwosComplement(d3._bits, d3._bits);
                BigInt.AddRaw(d3._bits, s2._bits, s2._bits);

                var res = s1;

                BigInt.AddRaw(res._bits, res._bits, res._bits);
                BigInt.AddRaw(res._bits, s5._bits, res._bits);
                BigInt.AddRaw(res._bits, s6._bits, res._bits);

                var toAdd = new BigInt[] { t, s2, s3, s4, d1 };

                foreach (var num in toAdd)
                {
                    var carry = BigInt.AddRaw(num._bits, res._bits, res._bits) == 1;
                    if (carry || res >= p)
                    {
                        BigInt.AddRaw(res._bits, negP._bits, res._bits);
                    }
                }
                s5.Clear();
                s6.Clear();
                d2.Clear();
                d3.Clear();
                foreach (var num in toAdd)
                {
                    num.Clear();
                }
                Clear();
                _bits = res._bits;
            }
示例#39
0
        /// <summary>
        /// Thread work to find a prime.
        /// </summary>
        private void FindPrime()
        {
            BigInt number;

              while (this.prime == null)
              {
            number = Prime.RandomNumber(bitLength).NextPrimeGMP();

            if (this.prime == null && number.IsProbablyPrimeRabinMiller(LowRabinMillerCount))
            {
              bool isPrime = true;

              for (int i = 0; i < 32 && this.prime == null && isPrime; i++)
              {
            isPrime &= number.IsProbablyPrimeRabinMiller(HighRabinMillerCount / 32);
              }

              if (isPrime)
              {
            this.prime = number;
              }
            }

            this.numberCount++;
              }
        }
示例#40
0
        private void FindSafePrimeOld()
        {
            BigInt number;
              BigInt doubleNumber;
              BigInt halfNumber;

              while (this.safePrime == null)
              {
            number = (this.prime + Prime.RandomNumber(bitLength)).NextPrimeGMP();
            doubleNumber = number * 2 + 1;
            halfNumber = (number - 1) / 2;

            if (this.safePrime == null && DivisiblyBySmallPrime(doubleNumber))
            {
              if (this.safePrime == null && doubleNumber.IsProbablyPrimeRabinMiller(LowRabinMillerCount))
              {
            if (this.safePrime == null && number.IsProbablyPrimeRabinMiller(HighRabinMillerCount))
            {
              if (this.safePrime == null && doubleNumber.IsProbablyPrimeRabinMiller(HighRabinMillerCount))
              {
                this.safePrime = doubleNumber;
              }
            }
              }
            }

            if (this.safePrime == null && DivisiblyBySmallPrime(halfNumber))
            {
              if (this.safePrime == null && halfNumber.IsProbablyPrimeRabinMiller(LowRabinMillerCount))
              {
            if (this.safePrime == null && number.IsProbablyPrimeRabinMiller(HighRabinMillerCount))
            {
              if (this.safePrime == null && halfNumber.IsProbablyPrimeRabinMiller(HighRabinMillerCount))
              {
                this.safePrime = number;
              }
            }
              }
            }
              }
        }
示例#41
0
        public void BitCountTest()
        {
            BigInt a = new BigInt(123456);

            Assert.AreEqual(6, a.BitCount());
        }
示例#42
0
    static void Main(string[] args)
    {
        var a = new BigInt();

        if (a.Sign != Sign.Plus || a.number.Equals(new List <int>()))
        {
            Console.WriteLine("Ошибка конструктора 1");
        }
        var b = new BigInt("+123");

        if (b.Sign != Sign.Plus || b.number.Equals(new List <int>()
        {
            1, 2, 3
        }))
        {
            Console.WriteLine("Ошибка конструктора 2");
        }
        var c = new BigInt("123");

        if (c.Sign != Sign.Plus || a.number.Equals(new List <int>()
        {
            1, 2, 3
        }))
        {
            Console.WriteLine("Ошибка конструктора 3");
        }
        var d = new BigInt("-123");

        if (d.Sign != Sign.Minus || d.number.Equals(new List <int>()
        {
            1, 2, 3
        }))
        {
            Console.WriteLine("Ошибка конструктора 4");
        }
        var e = new BigInt('-', new List <int>()
        {
            1, 2, 3
        });

        if (e.Sign != Sign.Minus || e.number.Equals(new List <int>()
        {
            1, 2, 3
        }))
        {
            Console.WriteLine("Ошибка конструктора 5");
        }

        var f = new BigInt("54321");
        var g = new BigInt("12345");
        var h = new BigInt("-123");
        var i = new BigInt("100");
        var j = new BigInt("-54321");
        var k = BigInt.zero;
        // var i = f + g;//66666
        //var j = f + h;//12222

        //Сложение тест
        var s1 = f + g;

        if (s1.ToString() != "66666")
        {
            Console.WriteLine("Ошибка сложения 1");
        }
        var s2 = f + h;

        if (s2.ToString() != "54198")
        {
            Console.WriteLine("Ошибка сложения 2");
        }
        var s3 = f + i;

        if (s3.ToString() != "54421")
        {
            Console.WriteLine("Ошибка сложения 3");
        }
        var s4 = j + i;

        if (s4.ToString() != "-54221")
        {
            Console.WriteLine("Ошибка сложения 4");
        }
        var s5 = g + j;

        if (s5.ToString() != "-41976")
        {
            Console.WriteLine("Ошибка сложения 4");
        }

        //Вычитание тест
        var sub1 = f - g;

        if (sub1.ToString() != "41976")
        {
            Console.WriteLine("Ошибка вычитания 1");
        }
        var sub2 = f - h;

        if (sub2.ToString() != "54444")
        {
            Console.WriteLine("Ошибка вычитания 2");
        }
        var sub3 = f - j;

        if (sub3.ToString() != "108642")
        {
            Console.WriteLine("Ошибка вычитания 3");
        }
        var sub4 = j - h;

        if (sub4.ToString() != "-54444")
        {
            Console.WriteLine("Ошибка вычитания 4");
        }
        var sub5 = g - j;

        if (sub5.ToString() != "66666")
        {
            Console.WriteLine("Ошибка вычитания 5");
        }

        //Умножение тест
        var m1 = f * g;

        if (m1.ToString() != "670592745")
        {
            Console.WriteLine("Ошибка умножения 1");
        }
        var m2 = f * h;

        if (m2.ToString() != "-6681483")
        {
            Console.WriteLine("Ошибка умножения 2");
        }
        var m3 = h * i;

        if (m3.ToString() != "-12300")
        {
            Console.WriteLine("Ошибка умножения 3");
        }
        var m4 = g * k;

        if (m4.ToString() != "0")
        {
            Console.WriteLine("Ошибка умножения 4");
        }
        var m5 = g * j;

        if (m5.ToString() != "-670592745")
        {
            Console.WriteLine("Ошибка умножения 5");
        }

        //Деление тест
        var d1 = f / g;

        if (d1.ToString() != "4")
        {
            Console.WriteLine("Ошибка деления 1");
        }
        var d2 = g / i;

        if (d2.ToString() != "123")
        {
            Console.WriteLine("Ошибка деления 2");
        }
        var d3 = j / i;

        if (d3.ToString() != "-543")
        {
            Console.WriteLine("Ошибка деления 3");
        }
        var d4 = j % i;

        if (d4.ToString() != "21")
        {
            Console.WriteLine("Ошибка деления 4");
        }
        var d5 = f % g;

        if (d5.ToString() != "4941")
        {
            Console.WriteLine("Ошибка деления 5");
        }
        var d6 = g % h;

        if (d6.ToString() != "45")
        {
            Console.WriteLine("Ошибка деления 6");
        }
        var d7 = h % g;

        if (d7.ToString() != "123")
        {
            Console.WriteLine("Ошибка деления 7");
        }
        var d8 = i / g;

        if (d8.ToString() != "0")
        {
            Console.WriteLine("Ошибка деления 8");
        }
        var d9 = new BigInt(143) % new BigInt(72);

        if (d9.ToString() != "71")
        {
            Console.WriteLine("Ошибка деления 9");
        }

        //Проверка на простое число тест
        var simple1 = new BigInt(3);

        if (!simple1.IsSimple())
        {
            Console.WriteLine("Ошибка простые числа 1");
        }
        var simple2 = new BigInt(37);

        if (!simple2.IsSimple())
        {
            Console.WriteLine("Ошибка простые числа 2");
        }
        var simple3 = new BigInt(103);

        if (!simple3.IsSimple())
        {
            Console.WriteLine("Ошибка простые числа 3");
        }
        var simple4 = new BigInt(179);

        if (!simple4.IsSimple())
        {
            Console.WriteLine("Ошибка простые числа 4");
        }
        var simple5 = new BigInt(28);

        if (simple5.IsSimple())
        {
            Console.WriteLine("Ошибка простые числа 5");
        }

        //RSA тест
        var rsa1 = new RSA();
        var rs1  = rsa1.MakeRSA(new BigInt(13), new BigInt(7), "test");

        if (rs1 != "TEST")
        {
            Console.WriteLine("Ошибка RSA 1");
        }
        var rsa2 = new RSA();
        var rs2  = rsa1.MakeRSA(new BigInt(7), new BigInt(17), "lab rabota");

        if (rs2 != "LAB RABOTA")
        {
            Console.WriteLine("Ошибка RSA 2");
        }
        //-----------------------------------------------------------

        var p   = "";
        var q   = "";
        var str = "";

        var xDoc = new XmlDocument();

        xDoc.Load("lab1.xml");
        var xRoot = xDoc.DocumentElement;

        foreach (XmlNode xNode in xRoot)
        {
            if (xNode.Name == "q")
            {
                q = xNode.InnerText;
            }
            if (xNode.Name == "p")
            {
                p = xNode.InnerText;
            }
            if (xNode.Name == "text")
            {
                str = xNode.InnerText;
            }
        }
        var rsa = new RSA();

        rsa.MakeRSA(new BigInt(p), new BigInt(q), str);
        Console.ReadKey();
    }
示例#43
0
 private static BigInt Mul10N(BigInt i,int n)
 {
     BigInt result = new BigInt();
     result.Digits = new List<int>(i.Digits);
     for (int j=0; j<n; j++)
         result.Digits.Insert(0,0);
     return result;
 }
示例#44
0
        public void BitLengthTest()
        {
            BigInt a = new BigInt(123456);

            Assert.AreEqual(17, a.BitLength());
        }
示例#45
0
        public static BigInt operator -(BigInt i1, BigInt i2)
        {
            int length = Math.Max(i1.Digits.Count, i2.Digits.Count);
            BigInt result = new BigInt();
            result.Digits = new List<int>(length + 1);

            int carry = 0;
            for (int i = 0; i < length; i++)
            {
                var tmp = (i1.Digits.Count > i ? i1.Digits[i] : 0) - (i2.Digits.Count > i ? i2.Digits[i] : 0) - carry;
                result.Digits.Add(tmp < 0 ? tmp+10 : tmp);
                carry = tmp < 0 ? 1 : 0;
            }
            result.RemoveLeadingZeros();
            return result;
        }
示例#46
0
        private static void RSAEncrypt(int length)
        {
            byte[] destinationArray = new byte[length];
            BigInt n        = null;
            BigInt exp      = null;
            BigInt integer3 = null;

            Array.Reverse(m_Exponent);
            Array.Reverse(m_Modulus);
            Array.Copy(m_Client_Random, 0, destinationArray, 0, length);
            Array.Reverse(destinationArray);

            if ((m_Modulus[0] & 0x80) != 0)
            {
                byte[] buffer2 = new byte[m_Modulus.Length + 1];
                Array.Copy(m_Modulus, 0, buffer2, 1, m_Modulus.Length);
                buffer2[0] = 0;
                n          = new BigInt(buffer2);
            }
            else
            {
                n = new BigInt(m_Modulus);
            }

            if ((m_Exponent[0] & 0x80) != 0)
            {
                byte[] buffer3 = new byte[m_Exponent.Length + 1];
                Array.Copy(m_Exponent, 0, buffer3, 1, m_Exponent.Length);
                buffer3[0] = 0;
                exp        = new BigInt(buffer3);
            }
            else
            {
                exp = new BigInt(m_Exponent);
            }

            if ((destinationArray[0] & 0x80) != 0)
            {
                byte[] buffer4 = new byte[destinationArray.Length + 1];
                Array.Copy(destinationArray, 0, buffer4, 1, destinationArray.Length);
                buffer4[0] = 0;
                integer3   = new BigInt(buffer4);
            }
            else
            {
                integer3 = new BigInt(destinationArray);
            }

            m_Sec_Crypted_Random = integer3.modPow(exp, n).getBytes();

            if (m_Sec_Crypted_Random.Length > modulus_size)
            {
                // sec_crypted_random too big!
            }

            Array.Reverse(m_Sec_Crypted_Random);

            if (m_Sec_Crypted_Random.Length < modulus_size)
            {
                byte[] buffer5 = new byte[modulus_size];
                Array.Copy(m_Sec_Crypted_Random, 0, buffer5, 0, m_Sec_Crypted_Random.Length);
                m_Sec_Crypted_Random = buffer5;
            }
        }
示例#47
0
        /// <summary>
        /// Tests wether or not any of the number is divisible by any small prime.
        /// </summary>
        /// <param name="number">Number to test.</param>
        /// <param name="doubleNumber">Number to test.</param>
        /// <returns>Could they both be prime?</returns>
        private bool DivisiblyBySmallPrime(BigInt number, BigInt doubleNumber)
        {
            foreach (int smallPrime in SmallPrimes)
              {
            if (number.IsDivisibleBy(smallPrime))
              return false;

            if (doubleNumber.IsDivisibleBy(smallPrime))
              return false;
              }

              return true;
        }
示例#48
0
        public void RunBBSWithPAndQTest(string TestFile)
        {
            List <TestData> TestSets = DataLoader.LoadData(TestFile);

            foreach (TestData TestSet in TestSets)
            {
                string RHexVal = "", RDecVal = "", PHexVal = "", PDecVal = "", QHexVal = "", QDecVal = "",
                              ZHexVal = "", ZDecVal = "", BHexVal = "", BDecVal = "";


                TestSet.Parameters.TryGetValue("r", out RHexVal);
                TestSet.Parameters.TryGetValue("R", out RDecVal);
                TestSet.Parameters.TryGetValue("p", out PHexVal);
                TestSet.Parameters.TryGetValue("P", out PDecVal);
                TestSet.Parameters.TryGetValue("q", out QHexVal);
                TestSet.Parameters.TryGetValue("Q", out QDecVal);
                TestSet.Parameters.TryGetValue("b", out BHexVal);
                TestSet.Parameters.TryGetValue("B", out BDecVal);
                BigInt R    = new BigInt(TestSet.Size, RHexVal);
                BigInt RDec = new BigInt(TestSet.Size, RDecVal);
                BigInt P    = new BigInt(TestSet.Size, PHexVal);
                BigInt PDec = new BigInt(TestSet.Size, PDecVal);
                BigInt Q    = new BigInt(TestSet.Size, QHexVal);
                BigInt QDec = new BigInt(TestSet.Size, QDecVal);
                BigInt B    = new BigInt(TestSet.Size, BHexVal);
                BigInt BDec = new BigInt(TestSet.Size, BDecVal);

                BBS       Bbs    = new BBS(R, P, Q);
                BBS       BbsDec = new BBS(RDec, PDec, QDec);
                BigInt [] Z      = new BigInt[16], ZDec = new BigInt[16], ZBBSCal = new BigInt[16], ZDecBBSCal = new BigInt[16];
                Bbs.GetRandomBBS(ref ZBBSCal);
                BbsDec.GetRandomBBS(ref ZDecBBSCal);

                for (int i = 0; i < 16; i++)
                {
                    if (i == 0)
                    {
                        TestSet.Parameters.TryGetValue("z", out ZHexVal);
                        TestSet.Parameters.TryGetValue("Z", out ZDecVal);
                        Z[i]    = new BigInt(TestSet.Size, ZHexVal);
                        ZDec[i] = new BigInt(TestSet.Size, ZDecVal);
                    }
                    else
                    {
                        TestSet.Parameters.TryGetValue($"z{i}", out ZHexVal);
                        TestSet.Parameters.TryGetValue($"Z{i}", out ZDecVal);
                        Z[i]    = new BigInt(TestSet.Size, ZHexVal);
                        ZDec[i] = new BigInt(TestSet.Size, ZDecVal);
                    }

                    Assert.True(ZBBSCal[i] == Z[i], $"Expected ZBBSCal[i] to be equal to Z[i]: {Z[i]}, but got wrong value: {TestSet.Title}.");
                    Assert.True(ZDecBBSCal[i] == ZDec[i], $"Expected ZDecBBSCal[i] to be equal to ZDec[i]: {ZDec[i]}, but got wrong value: {TestSet.Title}.");
                }

                BigInt BCal    = BBS.GetRandomBBSAsBigInt(ZBBSCal);
                BigInt BDecCal = BBS.GetRandomBBSAsBigInt(ZDecBBSCal);

                Assert.True(BCal == B, $"Expected B to be equal to BCal, but got wrong value: {TestSet.Title}.");
                Assert.True(BDecCal == BDec, $"Expected BDec to be equal to BDecCal, but got wrong value: {TestSet.Title}.");
            }
        }
示例#49
0
        /// <summary>
        /// Thread work to find a safe prime.
        /// </summary>
        private void FindSafePrime()
        {
            BigInt number;
              BigInt doubleNumber;

              while (this.safePrime == null)
              {
            number = (this.prime + Prime.RandomNumber(bitLength));
            if (number.IsEven) number++;
            doubleNumber = number * 2 + 1;

            if (DivisiblyBySmallPrime(number, doubleNumber))
            {
              if (number.IsProbablyPrimeRabinMiller(LowRabinMillerCount))
              {
            if (doubleNumber.IsProbablyPrimeRabinMiller(LowRabinMillerCount))
            {
              if (number.IsProbablyPrimeRabinMiller(HighRabinMillerCount))
              {
                if (doubleNumber.IsProbablyPrimeRabinMiller(HighRabinMillerCount))
                {
                  this.safePrime = doubleNumber;
                }
              }
            }

            this.primeCount++;
              }
            }

            this.numberCount++;
              }
        }
示例#50
0
        public void RunFindPBBSTest(string TestFile)
        {
            List <TestData> TestSets = DataLoader.LoadData(TestFile);

            foreach (TestData TestSet in TestSets)
            {
                string AHexVal = "", ADecVal = "", PHexVal = "", PDecVal = "";
                TestSet.Parameters.TryGetValue("a", out AHexVal);
                TestSet.Parameters.TryGetValue("A", out ADecVal);
                BigInt A    = new BigInt(TestSet.Size, AHexVal);
                BigInt ADec = new BigInt(TestSet.Size, ADecVal);

                BBS    Bbs = new BBS(A, (short)A.BitsCount(), true);
                BBS    BbsDec = new BBS(ADec, (short)ADec.BitsCount(), true);
                BigInt P = new BigInt(TestSet.Size, 0), PDec = new BigInt(TestSet.Size, 0), PCal = Bbs.P, PDecCal = BbsDec.P;
                for (int i = 0; i < 10; i++)
                {
                    if (i == 0)
                    {
                        TestSet.Parameters.TryGetValue("p", out PHexVal);
                        TestSet.Parameters.TryGetValue("P", out PDecVal);
                        P    = new BigInt(TestSet.Size, PHexVal);
                        PDec = new BigInt(TestSet.Size, PDecVal);
                        Assert.True(PCal == P, $"Expected P to be equal to PCal, but got wrong value: {TestSet.Title}.");
                        Assert.True(PDecCal == PDec, $"Expected PDec to be equal to PDecCal, but got wrong value: {TestSet.Title}.");
                    }
                    else
                    {
                        TestSet.Parameters.TryGetValue($"p{i}", out PHexVal);
                        TestSet.Parameters.TryGetValue($"P{i}", out PDecVal);
                        PCal    = BBS.GetNextBlumPrime(P);
                        PDecCal = BBS.GetNextBlumPrime(PDec);
                        P       = new BigInt(TestSet.Size, PHexVal);
                        PDec    = new BigInt(TestSet.Size, PDecVal);

                        Assert.True(PCal == P, $"Expected P to be equal to PCal, but got wrong value: {TestSet.Title}.");
                        Assert.True(PDecCal == PDec, $"Expected PDec to be equal to PDecCal, but got wrong value: {TestSet.Title}.");
                    }
                }
            }
        }
示例#51
0
        private bool SetVotingMaterial(VotingMaterial votingMaterial)
        {
            bool acceptMaterial = votingMaterial.Valid(CertificateStorage);

              if (acceptMaterial)
              {
            this.parameters = votingMaterial.Parameters.Value;
            this.publicKey = new BigInt(1);

            foreach (Signed<ShareResponse> signedShareResponse in votingMaterial.PublicKeyParts)
            {
              ShareResponse shareResponse = signedShareResponse.Value;
              this.publicKey = (this.publicKey * shareResponse.PublicKeyPart).Mod(this.parameters.P);
            }
              }

              return acceptMaterial;
        }
示例#52
0
 public DotPair(BigInt a, BigInt b, GameObject wall = null)
 {
     this.a    = (int)a;
     this.b    = (int)b;
     this.wall = wall;
 }
示例#53
0
 public void Simplify()
 {
     BigInt gcd = GCD(Nominator, Denominator);
     Nominator /= gcd;
     Denominator /= gcd;
 }
示例#54
0
 public static void ComparisonTest(string first, string second, int expected)
 {
     Assert.AreEqual(expected, BigInt.Comparison(new BigInt(first), new BigInt(second)));
 }