Equals() public method

public Equals ( object o ) : bool
o object
return bool
Ejemplo n.º 1
0
        /// <summary>
        /// Runs the EEA on two BigIntegers
        /// </summary>
        /// <param name="A">Quotient A</param>
        /// <param name="B">Quotient B</param>
        /// <returns>Return a BigIntEuclidean object that contains the result in the variables X, Y, and GCD</returns>
        /// 
        /// <remarks>
        /// Implemented from pseudocode on <a href="http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm"/>Wikipedia
        /// </remarks>
        public static BigIntEuclidean Calculate(BigInteger A, BigInteger B)
        {
            BigInteger x = BigInteger.Zero;
            BigInteger lastX = BigInteger.One;
            BigInteger y = BigInteger.One;
            BigInteger lastY = BigInteger.Zero;

            while (!B.Equals(BigInteger.Zero))
            {
                BigInteger[] quotientAndRemainder = A.DivideAndRemainder(B);
                BigInteger quotient = quotientAndRemainder[0];
                BigInteger temp = A;

                A = B;
                B = quotientAndRemainder[1];

                temp = x;
                x = lastX.Subtract(quotient.Multiply(x));
                lastX = temp;

                temp = y;
                y = lastY.Subtract(quotient.Multiply(y));
                lastY = temp;
            }

            BigIntEuclidean result = new BigIntEuclidean();
            result.X = lastX;
            result.Y = lastY;
            result.GCD = A;

            return result;
        }
Ejemplo n.º 2
0
        /** @see BigInteger#andNot(BigInteger) */
        public static BigInteger AndNot(BigInteger val, BigInteger that)
        {
            if (that.Sign == 0) {
                return val;
            }
            if (val.Sign == 0) {
                return BigInteger.Zero;
            }
            if (val.Equals(BigInteger.MinusOne)) {
                return that.Not();
            }
            if (that.Equals(BigInteger.MinusOne)) {
                return BigInteger.Zero;
            }

            //if val == that, return 0

            if (val.Sign > 0) {
                if (that.Sign > 0) {
                    return AndNotPositive(val, that);
                } else {
                    return AndNotPositiveNegative(val, that);
                }
            } else {
                if (that.Sign > 0) {
                    return AndNotNegativePositive(val, that);
                } else {
                    return AndNotNegative(val, that);
                }
            }
        }
Ejemplo n.º 3
0
        /** @see BigInteger#and(BigInteger) */
        public static BigInteger And(BigInteger val, BigInteger that)
        {
            if (that.Sign == 0 || val.Sign == 0) {
                return BigInteger.Zero;
            }
            if (that.Equals(BigInteger.MinusOne)) {
                return val;
            }
            if (val.Equals(BigInteger.MinusOne)) {
                return that;
            }

            if (val.Sign > 0) {
                if (that.Sign > 0) {
                    return AndPositive(val, that);
                } else {
                    return AndDiffSigns(val, that);
                }
            } else {
                if (that.Sign > 0) {
                    return AndDiffSigns(that, val);
                } else if (val.numberLength > that.numberLength) {
                    return AndNegative(val, that);
                } else {
                    return AndNegative(that, val);
                }
            }
        }
Ejemplo n.º 4
0
		public static BigInteger ValidatePublicValue(BigInteger N, BigInteger val)
		{
		    val = val.Mod(N);

	        // Check that val % N != 0
	        if (val.Equals(BigInteger.Zero))
	            throw new CryptoException("Invalid public value: 0");

		    return val;
		}
Ejemplo n.º 5
0
        /// <summary>
        /// Returns a new BigInteger whose value is ~Value.
        /// <para>The result of this operation is <c>-this-1</c>.</para>
        /// </summary>
        /// 
        /// <param name="Value">Value to be Not'ed</param>
        /// 
        /// <returns>Returns <c>~Value</c></returns>
        internal static BigInteger Not(BigInteger Value)
        {
            if (Value._sign == 0)
                return BigInteger.MinusOne;
            if (Value.Equals(BigInteger.MinusOne))
                return BigInteger.Zero;

            int[] resDigits = new int[Value._numberLength + 1];
            int i;

            if (Value._sign > 0)
            {
                // ~val = -val + 1
                if (Value._digits[Value._numberLength - 1] != -1)
                {
                    for (i = 0; Value._digits[i] == -1; i++)
                    {
                        ;
                    }
                }
                else
                {
                    for (i = 0; (i < Value._numberLength) && (Value._digits[i] == -1); i++)
                    {
                        ;
                    }
                    if (i == Value._numberLength)
                    {
                        resDigits[i] = 1;
                        return new BigInteger(-Value._sign, i + 1, resDigits);
                    }
                }
                // Here a carry 1 was generated
            }
            else
            {
                // ~val = -val - 1
                for (i = 0; Value._digits[i] == 0; i++)
                    resDigits[i] = -1;
            }

            // Now, the carry/borrow can be absorbed
            resDigits[i] = Value._digits[i] + Value._sign;
            // Copying the remaining unchanged digit
            for (i++; i < Value._numberLength; i++)
                resDigits[i] = Value._digits[i];

            return new BigInteger(-Value._sign, i, resDigits);
        }
Ejemplo n.º 6
0
        private static bool VerifyCtorInt32(Int32 value)
        {
            bool ret = true;
            BigInteger bigInteger;

            bigInteger = new BigInteger(value);

            if (!bigInteger.Equals(value))
            {
                Console.WriteLine("Expected BigInteger {0} to be equal to Int32 {1}", bigInteger, value);
                ret = false;
            }
            if (String.CompareOrdinal(value.ToString(), bigInteger.ToString()) != 0)
            {
                Console.WriteLine("Int32.ToString() and BigInteger.ToString() on {0} and {1} should be equal", value, bigInteger);
                ret = false;
            }
            if (value != (Int32)bigInteger)
            {
                Console.WriteLine("Expected BigInteger {0} to be equal to Int32 {1}", bigInteger, value);
                ret = false;
            }

            if (value != Int32.MaxValue)
            {
                if ((Int32)(value + 1) != (Int32)(bigInteger + 1))
                {
                    Console.WriteLine("Adding 1 to both {0} and {1} should remain equal", value, bigInteger);
                    ret = false;
                }
            }

            if (value != Int32.MinValue)
            {
                if ((Int32)(value - 1) != (Int32)(bigInteger - 1))
                {
                    Console.WriteLine("Subtracting 1 from both {0} and {1} should remain equal", value, bigInteger);
                    ret = false;
                }
            }

            Assert.True(VerifyBigintegerUsingIdentities(bigInteger, 0 == value), " Verification Failed");

            return ret;
        }
		/**
		* Generate a suitable blind factor for the public key the generator was initialised with.
		*
		* @return a random blind factor
		*/
		public BigInteger GenerateBlindingFactor()
		{
			if (key == null)
				throw new InvalidOperationException("generator not initialised");

			BigInteger m = key.Modulus;
			int length = m.BitLength - 1; // must be less than m.BitLength
			BigInteger factor;
			BigInteger gcd;

			do
			{
				factor = new BigInteger(length, random);
				gcd = factor.Gcd(m);
			}
			while (factor.Sign == 0 || factor.Equals(BigInteger.One) || !gcd.Equals(BigInteger.One));

			return factor;
		}
Ejemplo n.º 8
0
        public override bool Equals(object o)
        {
            if (this == o)
            {
                return(true);
            }

            if (o == null || !(o is ECKeyPair))
            {
                return(false);
            }

            var ecKeyPair = (ECKeyPair)o;

            if (!_privateKey?.Equals(ecKeyPair._privateKey) ?? ecKeyPair._privateKey != null)
            {
                return(false);
            }

            return(_publicKey?.Equals(ecKeyPair._publicKey) ?? ecKeyPair._publicKey == null);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Computes the square root of a BigInteger modulo a prime employing the Shanks-Tonelli algorithm
        /// </summary>
        /// 
        /// <param name="X">The value out of which we extract the square root</param>
        /// <param name="P">The prime modulus that determines the underlying field</param>
        /// 
        /// <returns>Returns a number <c>B</c> such that B^2 = A (mod P) if <c>A</c> is a quadratic residue modulo <c>P</c></returns>
        public static BigInteger Ressol(BigInteger X, BigInteger P)
        {
            BigInteger v = null;

            if (X.CompareTo(ZERO) < 0)
                X = X.Add(P);
            if (X.Equals(ZERO))
                return ZERO;
            if (P.Equals(TWO))
                return X;

            // p = 3 mod 4
            if (P.TestBit(0) && P.TestBit(1))
            {
                if (Jacobi(X, P) == 1)
                {
                    // a quadr. residue mod p
                    v = P.Add(ONE); // v = p+1
                    v = v.ShiftRight(2); // v = v/4
                    return X.ModPow(v, P); // return a^v mod p
                }
                throw new ArgumentException("No quadratic residue: " + X + ", " + P);
            }

            long t = 0;

            // initialization
            // compute k and s, where p = 2^s (2k+1) +1

            BigInteger k = P.Subtract(ONE); // k = p-1
            long s = 0;
            while (!k.TestBit(0))
            { // while k is even
                s++; // s = s+1
                k = k.ShiftRight(1); // k = k/2
            }

            k = k.Subtract(ONE); // k = k - 1
            k = k.ShiftRight(1); // k = k/2

            // initial values
            BigInteger r = X.ModPow(k, P); // r = a^k mod p

            BigInteger n = r.Multiply(r).Remainder(P); // n = r^2 % p
            n = n.Multiply(X).Remainder(P); // n = n * a % p
            r = r.Multiply(X).Remainder(P); // r = r * a %p

            if (n.Equals(ONE))
            {
                return r;
            }

            // non-quadratic residue
            BigInteger z = TWO; // z = 2
            while (Jacobi(z, P) == 1)
            {
                // while z quadratic residue
                z = z.Add(ONE); // z = z + 1
            }

            v = k;
            v = v.Multiply(TWO); // v = 2k
            v = v.Add(ONE); // v = 2k + 1
            BigInteger c = z.ModPow(v, P); // c = z^v mod p

            // iteration
            while (n.CompareTo(ONE) == 1)
            { // n > 1
                k = n; // k = n
                t = s; // t = s
                s = 0;

                while (!k.Equals(ONE))
                { // k != 1
                    k = k.Multiply(k).Mod(P); // k = k^2 % p
                    s++; // s = s + 1
                }

                t -= s; // t = t - s
                if (t == 0)
                {
                    throw new ArgumentException("No quadratic residue: " + X + ", " + P);
                }

                v = ONE;
                for (long i = 0; i < t - 1; i++)
                {
                    v = v.ShiftLeft(1); // v = 1 * 2^(t - 1)
                }
                c = c.ModPow(v, P); // c = c^v mod p
                r = r.Multiply(c).Remainder(P); // r = r * c % p
                c = c.Multiply(c).Remainder(P); // c = c^2 % p
                n = n.Multiply(c).Mod(P); // n = n * c % p
            }
            return r;
        }
Ejemplo n.º 10
0
 public void Equals_BI_on_same_is_true()
 {
     BigInteger i = new BigInteger(1, 0x1, 0x2, 0x3);
     BigInteger j = new BigInteger(1, 0x1, 0x2, 0x3);
     Expect(i.Equals(j));
 }
Ejemplo n.º 11
0
        private static bool VerifyCtorByteArray(byte[] value, UInt64 expectedValue)
        {
            bool ret = true;
            BigInteger bigInteger;

            bigInteger = new BigInteger(value);

            if (!bigInteger.Equals(expectedValue))
            {
                Console.WriteLine("Expected BigInteger {0} to be equal to UInt64 {1}", bigInteger, expectedValue);
                ret = false;
            }
            if (!expectedValue.ToString().Equals(bigInteger.ToString(), StringComparison.OrdinalIgnoreCase))
            {
                Console.WriteLine("UInt64.ToString() and BigInteger.ToString()");
                ret = false;
            }
            if (expectedValue != (UInt64)bigInteger)
            {
                Console.WriteLine("BigInteger casted to a UInt64");
                ret = false;
            }

            if (expectedValue != UInt64.MaxValue)
            {
                if ((UInt64)(expectedValue + 1) != (UInt64)(bigInteger + 1))
                {
                    Console.WriteLine("BigInteger added to 1");
                    ret = false;
                }
            }

            if (expectedValue != UInt64.MinValue)
            {
                if ((UInt64)(expectedValue - 1) != (UInt64)(bigInteger - 1))
                {
                    Console.WriteLine("BigInteger subtracted by 1");
                    ret = false;
                }
            }

            Assert.True(VerifyCtorByteArray(value), " Verification Failed");
            return ret;
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Verifies that the server's proof value matches the value
        /// calculated by the client.
        /// </summary>
        /// <param name="serverProof">The 20-byte server proof.</param>
        /// <exception cref="ArgumentOutOfRangeException">Thrown if 
        /// the server proof value is not exactly 20 bytes.</exception>
        /// <exception cref="InvalidOperationException">Thrown if the object has not 
        /// yet been initialized.</exception>
        /// <remarks>
        /// This method should be called after the <see cref="LoginProof(byte[], int, int, byte[], byte[])">LoginProof</see> method.
        /// </remarks>
        /// <returns><b>True</b> if the server proof is valid; 
        /// otherwise <b>false</b>.</returns>
        public bool VerifyServerProof(byte[] serverProof)
        {
            if (serverProof.Length != 20)
                throw new ArgumentOutOfRangeException(Resources.nlsServerProof20);

            MemoryStream ms_m2 = new MemoryStream(92);
            BinaryWriter bw = new BinaryWriter(ms_m2);
            bw.Write(EnsureArrayLength(A.GetBytes(), 32));
            bw.Write(m1.GetBytes());
            bw.Write(k);
            byte[] client_m2_data = ms_m2.GetBuffer();
            ms_m2.Close();

            byte[] client_hash_m2 = s_sha.ComputeHash(client_m2_data);
            BigInteger client_m2 = new BigInteger(client_hash_m2);
            BigInteger server_m2 = new BigInteger(serverProof);

            Debug.WriteLine(client_m2.ToHexString(), "Client");
            Debug.WriteLine(server_m2.ToHexString(), "Server");

            return client_m2.Equals(server_m2);
        }
Ejemplo n.º 13
0
 public void Equals_BI_on_different_is_false()
 {
     BigInteger i = new BigInteger(1, 0x1, 0x2, 0x3);
     BigInteger j = new BigInteger(1, 0x1, 0x2, 0x4);
     Expect(i.Equals(j),False);
 }
Ejemplo n.º 14
0
        public void ConstructorIRandom()
        {
            // regression test for HARMONY-1047
            Assert.Throws<OverflowException>(() => new BigInteger(Int32.MaxValue, (Random) null));

            bi = new BigInteger(70, rand);
            bi2 = new BigInteger(70, rand);
            Assert.IsTrue(bi.CompareTo(zero) >= 0, "Random number is negative");
            Assert.IsTrue(bi.CompareTo(twoToTheSeventy) < 0, "Random number is too big");
            Assert.IsTrue(!bi.Equals(bi2), "Two random numbers in a row are the same (might not be a bug but it very likely is)");
            Assert.IsTrue(new BigInteger(0, rand).Equals(BigInteger.Zero), "Not zero");
        }
 protected bool Equals(
     ECPrivateKeyParameters other)
 {
     return(d.Equals(other.d) && base.Equals(other));
 }
Ejemplo n.º 16
0
        public void doTestCurve(
            string name)
        {
//			ECGenParameterSpec ecSpec = new ECGenParameterSpec(name);
            ECDomainParameters ecSpec = GetCurveParameters(name);

            IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("ECDH");

//			g.initialize(ecSpec, new SecureRandom());
            g.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom()));

            //
            // a side
            //
            AsymmetricCipherKeyPair aKeyPair = g.GenerateKeyPair();

//			KeyAgreement aKeyAgree = KeyAgreement.getInstance("ECDHC");
            IBasicAgreement aKeyAgree = AgreementUtilities.GetBasicAgreement("ECDHC");

            aKeyAgree.Init(aKeyPair.Private);

            //
            // b side
            //
            AsymmetricCipherKeyPair bKeyPair = g.GenerateKeyPair();

//			KeyAgreement bKeyAgree = KeyAgreement.getInstance("ECDHC");
            IBasicAgreement bKeyAgree = AgreementUtilities.GetBasicAgreement("ECDHC");

            bKeyAgree.Init(bKeyPair.Private);

            //
            // agreement
            //
//			aKeyAgree.doPhase(bKeyPair.Public, true);
//			bKeyAgree.doPhase(aKeyPair.Public, true);
//
//			BigInteger k1 = new BigInteger(aKeyAgree.generateSecret());
//			BigInteger k2 = new BigInteger(bKeyAgree.generateSecret());
            BigInteger k1 = aKeyAgree.CalculateAgreement(bKeyPair.Public);
            BigInteger k2 = bKeyAgree.CalculateAgreement(aKeyPair.Public);

            if (!k1.Equals(k2))
            {
                Fail("2-way test failed");
            }

            //
            // public key encoding test
            //
//			byte[]              pubEnc = aKeyPair.Public.getEncoded();
            byte[] pubEnc = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(aKeyPair.Public).GetDerEncoded();

//			KeyFactory          keyFac = KeyFactory.getInstance("ECDH");
//			X509EncodedKeySpec  pubX509 = new X509EncodedKeySpec(pubEnc);
//			ECPublicKey         pubKey = (ECPublicKey)keyFac.generatePublic(pubX509);
            ECPublicKeyParameters pubKey = (ECPublicKeyParameters)PublicKeyFactory.CreateKey(pubEnc);

//			if (!pubKey.getW().Equals(((ECPublicKey)aKeyPair.Public).getW()))
            if (!pubKey.Q.Equals(((ECPublicKeyParameters)aKeyPair.Public).Q))
            {
                Fail("public key encoding (Q test) failed");
            }

            // TODO Put back in?
//			if (!(pubKey.getParams() is ECNamedCurveSpec))
//			{
//				Fail("public key encoding not named curve");
//			}

            //
            // private key encoding test
            //
//			byte[]              privEnc = aKeyPair.Private.getEncoded();
            byte[] privEnc = PrivateKeyInfoFactory.CreatePrivateKeyInfo(aKeyPair.Private).GetDerEncoded();

//			PKCS8EncodedKeySpec privPKCS8 = new PKCS8EncodedKeySpec(privEnc);
//			ECPrivateKey        privKey = (ECPrivateKey)keyFac.generatePrivate(privPKCS8);
            ECPrivateKeyParameters privKey = (ECPrivateKeyParameters)PrivateKeyFactory.CreateKey(privEnc);

//			if (!privKey.getS().Equals(((ECPrivateKey)aKeyPair.Private).getS()))
            if (!privKey.D.Equals(((ECPrivateKeyParameters)aKeyPair.Private).D))
            {
                Fail("private key encoding (S test) failed");
            }

            // TODO Put back in?
//			if (!(privKey.getParams() is ECNamedCurveSpec))
//			{
//				Fail("private key encoding not named curve");
//			}
//
//			ECNamedCurveSpec privSpec = (ECNamedCurveSpec)privKey.getParams();
//			if (!(privSpec.GetName().Equals(name) || privSpec.GetName().Equals(CurveNames.get(name))))
//			{
//				Fail("private key encoding wrong named curve. Expected: "
//					+ CurveNames[name] + " got " + privSpec.GetName());
//			}
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Returns a new BigInteger whose value is <c>this ^ Value</c>
        /// </summary>
        /// 
        /// <param name="Value">Value to be Xor'ed </param>
        /// <param name="X">The second value</param>
        /// 
        /// <returns>Returns <c>this ^ Value</c></returns>
        internal static BigInteger Xor(BigInteger Value, BigInteger X)
        {
            if (X._sign == 0)
                return Value;
            if (Value._sign == 0)
                return X;
            if (X.Equals(BigInteger.MinusOne))
                return Value.Not();
            if (Value.Equals(BigInteger.MinusOne))
                return X.Not();

            if (Value._sign > 0)
            {
                if (X._sign > 0)
                {
                    if (Value._numberLength > X._numberLength)
                        return XorPositive(Value, X);
                    else
                        return XorPositive(X, Value);
                }
                else
                {
                    return XorDiffSigns(Value, X);
                }
            }
            else
            {
                if (X._sign > 0)
                    return XorDiffSigns(X, Value);
                else if (X.FirstNonzeroDigit > Value.FirstNonzeroDigit)
                    return XorNegative(X, Value);
                else
                    return XorNegative(Value, X);
            }
        }
Ejemplo n.º 18
0
 protected bool Equals(
     DsaPrivateKeyParameters other)
 {
     return(x.Equals(other.x) && base.Equals(other));
 }
Ejemplo n.º 19
0
        /**
         * FIPS 186-4 C.3.2 Enhanced Miller-Rabin Probabilistic Primality Test
         *
         * Run several iterations of the Miller-Rabin algorithm with randomly-chosen bases. This is an
         * alternative to {@link #isMRProbablePrime(BigInteger, SecureRandom, int)} that provides more
         * information about a composite candidate, which may be useful when generating or validating
         * RSA moduli.
         *
         * @param candidate
         *            the {@link BigInteger} instance to test for primality.
         * @param random
         *            the source of randomness to use to choose bases.
         * @param iterations
         *            the number of randomly-chosen bases to perform the test for.
         * @return an {@link MROutput} instance that can be further queried for details.
         */
        public static MROutput EnhancedMRProbablePrimeTest(BigInteger candidate, SecureRandom random, int iterations)
        {
            CheckCandidate(candidate, "candidate");

            if (random == null)
            {
                throw new ArgumentNullException("random");
            }
            if (iterations < 1)
            {
                throw new ArgumentException("must be > 0", "iterations");
            }

            if (candidate.BitLength == 2)
            {
                return(MROutput.ProbablyPrime());
            }

            if (!candidate.TestBit(0))
            {
                return(MROutput.ProvablyCompositeWithFactor(Two));
            }

            BigInteger w       = candidate;
            BigInteger wSubOne = candidate.Subtract(One);
            BigInteger wSubTwo = candidate.Subtract(Two);

            int        a = wSubOne.GetLowestSetBit();
            BigInteger m = wSubOne.ShiftRight(a);

            for (int i = 0; i < iterations; ++i)
            {
                BigInteger b = BigIntegers.CreateRandomInRange(Two, wSubTwo, random);
                BigInteger g = b.Gcd(w);

                if (g.CompareTo(One) > 0)
                {
                    return(MROutput.ProvablyCompositeWithFactor(g));
                }

                BigInteger z = b.ModPow(m, w);

                if (z.Equals(One) || z.Equals(wSubOne))
                {
                    continue;
                }

                bool primeToBase = false;

                BigInteger x = z;
                for (int j = 1; j < a; ++j)
                {
                    z = z.ModPow(Two, w);

                    if (z.Equals(wSubOne))
                    {
                        primeToBase = true;
                        break;
                    }

                    if (z.Equals(One))
                    {
                        break;
                    }

                    x = z;
                }

                if (!primeToBase)
                {
                    if (!z.Equals(One))
                    {
                        x = z;
                        z = z.ModPow(Two, w);

                        if (!z.Equals(One))
                        {
                            x = z;
                        }
                    }

                    g = x.Subtract(One).Gcd(w);

                    if (g.CompareTo(One) > 0)
                    {
                        return(MROutput.ProvablyCompositeWithFactor(g));
                    }

                    return(MROutput.ProvablyCompositeNotPrimePower());
                }
            }

            return(MROutput.ProbablyPrime());
        }
Ejemplo n.º 20
0
        /**
         * Computes the <code>[&#964;]</code>-adic window NAF of an element
         * <code>&#955;</code> of <code><b>Z</b>[&#964;]</code>.
         * @param mu The parameter &#956; of the elliptic curve.
         * @param lambda The element <code>&#955;</code> of
         * <code><b>Z</b>[&#964;]</code> of which to compute the
         * <code>[&#964;]</code>-adic NAF.
         * @param width The window width of the resulting WNAF.
         * @param pow2w 2<sup>width</sup>.
         * @param tw The auxiliary value <code>t<sub>w</sub></code>.
         * @param alpha The <code>&#945;<sub>u</sub></code>'s for the window width.
         * @return The <code>[&#964;]</code>-adic window NAF of
         * <code>&#955;</code>.
         */
        public static sbyte[] TauAdicWNaf(sbyte mu, ZTauElement lambda,
                                          sbyte width, BigInteger pow2w, BigInteger tw, ZTauElement[] alpha)
        {
            if (!((mu == 1) || (mu == -1)))
            {
                throw new ArgumentException("mu must be 1 or -1");
            }

            BigInteger norm = Norm(mu, lambda);

            // Ceiling of log2 of the norm
            int log2Norm = norm.BitLength;

            // If length(TNAF) > 30, then length(TNAF) < log2Norm + 3.52
            int maxLength = log2Norm > 30 ? log2Norm + 4 + width : 34 + width;

            // The array holding the TNAF
            sbyte[] u = new sbyte[maxLength];

            // 2^(width - 1)
            BigInteger pow2wMin1 = pow2w.ShiftRight(1);

            // Split lambda into two BigIntegers to simplify calculations
            BigInteger r0 = lambda.u;
            BigInteger r1 = lambda.v;
            int        i  = 0;

            // while lambda <> (0, 0)
            while (!((r0.Equals(BigInteger.Zero)) && (r1.Equals(BigInteger.Zero))))
            {
                // if r0 is odd
                if (r0.TestBit(0))
                {
                    // uUnMod = r0 + r1*tw Mod 2^width
                    BigInteger uUnMod
                        = r0.Add(r1.Multiply(tw)).Mod(pow2w);

                    sbyte uLocal;
                    // if uUnMod >= 2^(width - 1)
                    if (uUnMod.CompareTo(pow2wMin1) >= 0)
                    {
                        uLocal = (sbyte)uUnMod.Subtract(pow2w).IntValue;
                    }
                    else
                    {
                        uLocal = (sbyte)uUnMod.IntValue;
                    }
                    // uLocal is now in [-2^(width-1), 2^(width-1)-1]

                    u[i] = uLocal;
                    bool s = true;
                    if (uLocal < 0)
                    {
                        s      = false;
                        uLocal = (sbyte)-uLocal;
                    }
                    // uLocal is now >= 0

                    if (s)
                    {
                        r0 = r0.Subtract(alpha[uLocal].u);
                        r1 = r1.Subtract(alpha[uLocal].v);
                    }
                    else
                    {
                        r0 = r0.Add(alpha[uLocal].u);
                        r1 = r1.Add(alpha[uLocal].v);
                    }
                }
                else
                {
                    u[i] = 0;
                }

                BigInteger t = r0;

                if (mu == 1)
                {
                    r0 = r1.Add(r0.ShiftRight(1));
                }
                else
                {
                    // mu == -1
                    r0 = r1.Subtract(r0.ShiftRight(1));
                }
                r1 = t.ShiftRight(1).Negate();
                i++;
            }
            return(u);
        }
Ejemplo n.º 21
0
        /**
         * Computes the <code>&#964;</code>-adic NAF (non-adjacent form) of an
         * element <code>&#955;</code> of <code><b>Z</b>[&#964;]</code>.
         * @param mu The parameter <code>&#956;</code> of the elliptic curve.
         * @param lambda The element <code>&#955;</code> of
         * <code><b>Z</b>[&#964;]</code>.
         * @return The <code>&#964;</code>-adic NAF of <code>&#955;</code>.
         */
        public static sbyte[] TauAdicNaf(sbyte mu, ZTauElement lambda)
        {
            if (!((mu == 1) || (mu == -1)))
            {
                throw new ArgumentException("mu must be 1 or -1");
            }

            BigInteger norm = Norm(mu, lambda);

            // Ceiling of log2 of the norm
            int log2Norm = norm.BitLength;

            // If length(TNAF) > 30, then length(TNAF) < log2Norm + 3.52
            int maxLength = log2Norm > 30 ? log2Norm + 4 : 34;

            // The array holding the TNAF
            sbyte[] u = new sbyte[maxLength];
            int     i = 0;

            // The actual length of the TNAF
            int length = 0;

            BigInteger r0 = lambda.u;
            BigInteger r1 = lambda.v;

            while (!((r0.Equals(BigInteger.Zero)) && (r1.Equals(BigInteger.Zero))))
            {
                // If r0 is odd
                if (r0.TestBit(0))
                {
                    u[i] = (sbyte)BigInteger.Two.Subtract((r0.Subtract(r1.ShiftLeft(1))).Mod(Four)).IntValue;

                    // r0 = r0 - u[i]
                    if (u[i] == 1)
                    {
                        r0 = r0.ClearBit(0);
                    }
                    else
                    {
                        // u[i] == -1
                        r0 = r0.Add(BigInteger.One);
                    }
                    length = i;
                }
                else
                {
                    u[i] = 0;
                }

                BigInteger t = r0;
                BigInteger s = r0.ShiftRight(1);
                if (mu == 1)
                {
                    r0 = r1.Add(s);
                }
                else
                {
                    // mu == -1
                    r0 = r1.Subtract(s);
                }

                r1 = t.ShiftRight(1).Negate();
                i++;
            }

            length++;

            // Reduce the TNAF array to its actual length
            sbyte[] tnaf = new sbyte[length];
            Array.Copy(u, 0, tnaf, 0, length);
            return(tnaf);
        }
 public bool Equals(ECFieldElement other)
 {
     return(Value.Equals(other.Value));
 }
Ejemplo n.º 23
0
        /// <summary>
        /// Compute the next probable prime greater than <c>N</c> with the specified certainty
        /// </summary>
        /// 
        /// <param name="X">An integer number</param>
        /// <param name="Certainty">The certainty that the generated number is prime</param>
        /// 
        /// <returns>Returns the next prime greater than <c>N</c></returns>
        public static BigInteger NextProbablePrime(BigInteger X, int Certainty)
        {
            if (X.Signum() < 0 || X.Signum() == 0 || X.Equals(ONE))
                return TWO;

            BigInteger result = X.Add(ONE);

            // Ensure an odd number
            if (!result.TestBit(0))
                result = result.Add(ONE);

            while (true)
            {
                // Do cheap "pre-test" if applicable
                if (result.BitLength > 6)
                {
                    long r = result.Remainder(BigInteger.ValueOf(SMALL_PRIME_PRODUCT)).ToInt64();
                    if ((r % 3 == 0) || (r % 5 == 0) || (r % 7 == 0) ||
                        (r % 11 == 0) || (r % 13 == 0) || (r % 17 == 0) ||
                        (r % 19 == 0) || (r % 23 == 0) || (r % 29 == 0) ||
                        (r % 31 == 0) || (r % 37 == 0) || (r % 41 == 0))
                    {
                        result = result.Add(TWO);
                        continue; // Candidate is composite; try another
                    }
                }

                // All candidates of bitLength 2 and 3 are prime by this point
                if (result.BitLength < 4)
                    return result;

                // The expensive test
                if (result.IsProbablePrime(Certainty))
                    return result;

                result = result.Add(TWO);
            }
        }
Ejemplo n.º 24
0
        public virtual bool Match(
            object obj)
        {
            X509Certificate c = obj as X509Certificate;

            if (c == null)
            {
                return(false);
            }

            if (!MatchExtension(authorityKeyIdentifier, c, X509Extensions.AuthorityKeyIdentifier))
            {
                return(false);
            }

            if (basicConstraints != -1)
            {
                int bc = c.GetBasicConstraints();

                if (basicConstraints == -2)
                {
                    if (bc != -1)
                    {
                        return(false);
                    }
                }
                else
                {
                    if (bc < basicConstraints)
                    {
                        return(false);
                    }
                }
            }

            if (certificate != null && !certificate.Equals(c))
            {
                return(false);
            }

            if (certificateValid != null && !c.IsValid(certificateValid.Value))
            {
                return(false);
            }

            if (extendedKeyUsage != null)
            {
                IList eku = c.GetExtendedKeyUsage();

                // Note: if no extended key usage set, all key purposes are implicitly allowed

                if (eku != null)
                {
                    foreach (DerObjectIdentifier oid in extendedKeyUsage)
                    {
                        if (!eku.Contains(oid.Id))
                        {
                            return(false);
                        }
                    }
                }
            }

            if (issuer != null && !issuer.Equivalent(c.IssuerDN, true))
            {
                return(false);
            }

            if (keyUsage != null)
            {
                bool[] ku = c.GetKeyUsage();

                // Note: if no key usage set, all key purposes are implicitly allowed

                if (ku != null)
                {
                    for (int i = 0; i < 9; ++i)
                    {
                        if (keyUsage[i] && !ku[i])
                        {
                            return(false);
                        }
                    }
                }
            }

            if (policy != null)
            {
                Asn1OctetString extVal = c.GetExtensionValue(X509Extensions.CertificatePolicies);
                if (extVal == null)
                {
                    return(false);
                }

                Asn1Sequence certPolicies = Asn1Sequence.GetInstance(
                    X509ExtensionUtilities.FromExtensionValue(extVal));

                if (policy.Count < 1 && certPolicies.Count < 1)
                {
                    return(false);
                }

                bool found = false;
                foreach (PolicyInformation pi in certPolicies)
                {
                    if (policy.Contains(pi.PolicyIdentifier))
                    {
                        found = true;
                        break;
                    }
                }

                if (!found)
                {
                    return(false);
                }
            }

            if (privateKeyValid != null)
            {
                Asn1OctetString extVal = c.GetExtensionValue(X509Extensions.PrivateKeyUsagePeriod);
                if (extVal == null)
                {
                    return(false);
                }

                PrivateKeyUsagePeriod pkup = PrivateKeyUsagePeriod.GetInstance(
                    X509ExtensionUtilities.FromExtensionValue(extVal));

                DateTime dt        = privateKeyValid.Value;
                DateTime notAfter  = pkup.NotAfter.ToDateTime();
                DateTime notBefore = pkup.NotBefore.ToDateTime();

                if (dt.CompareTo(notAfter) > 0 || dt.CompareTo(notBefore) < 0)
                {
                    return(false);
                }
            }

            if (serialNumber != null && !serialNumber.Equals(c.SerialNumber))
            {
                return(false);
            }

            if (subject != null && !subject.Equivalent(c.SubjectDN, true))
            {
                return(false);
            }

            if (!MatchExtension(subjectKeyIdentifier, c, X509Extensions.SubjectKeyIdentifier))
            {
                return(false);
            }

            if (subjectPublicKey != null && !subjectPublicKey.Equals(GetSubjectPublicKey(c)))
            {
                return(false);
            }

            if (subjectPublicKeyAlgID != null &&
                !subjectPublicKeyAlgID.Equals(GetSubjectPublicKey(c).AlgorithmID))
            {
                return(false);
            }

            return(true);
        }
Ejemplo n.º 25
0
 public virtual bool Equals(
     FpFieldElement other)
 {
     return(q.Equals(other.q) && base.Equals(other));
 }
Ejemplo n.º 26
0
        /// <summary>
        /// Computes the bit per bit operator between this number and the given one.
        /// </summary>
        /// 
        /// <param name="Value">The value to be And'ed with X</param>
        /// <param name="X">The second value</param>
        /// 
        /// <returns>
        /// Returns a new BigInteger whose value is <c>Value &amp; X</c>.
        /// </returns>
        internal static BigInteger And(BigInteger Value, BigInteger X)
        {
            if (X._sign == 0 || Value._sign == 0)
                return BigInteger.Zero;
            if (X.Equals(BigInteger.MinusOne))
                return Value;
            if (Value.Equals(BigInteger.MinusOne))
                return X;

            if (Value._sign > 0)
            {
                if (X._sign > 0)
                    return AndPositive(Value, X);
                else
                    return AndDiffSigns(Value, X);
            }
            else
            {
                if (X._sign > 0)
                    return AndDiffSigns(X, Value);
                else if (Value._numberLength > X._numberLength)
                    return AndNegative(Value, X);
                else
                    return AndNegative(X, Value);
            }
        }
Ejemplo n.º 27
0
        private static void CheckNormaliseBaseTenResult(ExpandedDouble orig, NormalisedDecimal result)
        {
            String sigDigs = result.GetSignificantDecimalDigits();
            BigInteger frac = orig.GetSignificand();
            while (frac.BitLength() + orig.GetBinaryExponent() < 200)
            {
                frac = frac * (BIG_POW_10);
            }
            int binaryExp = orig.GetBinaryExponent() - orig.GetSignificand().BitLength();

            String origDigs = (frac << (binaryExp + 1)).ToString(10);

            if (!origDigs.StartsWith(sigDigs))
            {
                throw new AssertionException("Expected '" + origDigs + "' but got '" + sigDigs + "'.");
            }

            double dO = Double.Parse("0." + origDigs.Substring(sigDigs.Length));
            double d1 = Double.Parse(result.GetFractionalPart().ToString());
            BigInteger subDigsO = new BigInteger((int)(dO * 32768 + 0.5));
            BigInteger subDigsB = new BigInteger((int)(d1 * 32768 + 0.5));

            if (subDigsO.Equals(subDigsB))
            {
                return;
            }
            BigInteger diff = (subDigsB - subDigsO).Abs();
            if (diff.IntValue() > 100)
            {
                // 100/32768 ~= 0.003
                throw new AssertionException("minor mistake");
            }
        }
Ejemplo n.º 28
0
        public void ConstructorIBytes()
        {
            var myByteArray = new byte[] { (byte)0xFF, (byte)0xFE };
            bi = new BigInteger(1, myByteArray);
            IsTrue(bi.Equals(BigInteger.Zero.SetBit(16).Subtract(two)), "Incorrect value for pos number");
            bi = new BigInteger(-1, myByteArray);
            IsTrue(bi.Equals(BigInteger.Zero.SetBit(16).Subtract(two).Negate()), "Incorrect value for neg number");
            myByteArray = new byte[] { (byte)0, (byte)0 };
            bi = new BigInteger(0, myByteArray);
            IsTrue(bi.Equals(zero), "Incorrect value for zero");
            myByteArray = new byte[] { (byte)1 };

            Throw(() => new BigInteger(0, myByteArray), "BigInteger: failed constructor test");
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Validates a Warcraft III server signature.
        /// </summary>
        /// <param name="serverSignature">The server signature from 
        /// Battle.net's SID_AUTH_INFO message.</param>
        /// <param name="ipAddress">The IPv4 address of the server
        /// currently connected-to.</param>
        /// <returns><b>True</b> if the signature matches; 
        /// otherwise <b>false</b>.</returns>
        /// <exception cref="ArgumentOutOfRangeException">Thrown if 
        /// the server signature is not exactly 128 bytes.</exception>
        public static bool ValidateServerSignature(byte[] serverSignature,
            byte[] ipAddress)
        {
            // code based on iago's code.

            if (serverSignature.Length != 128)
                throw new ArgumentOutOfRangeException(Resources.nlsSrvSig128);

            BigInteger key = new BigInteger(new byte[] { 0, 1, 0, 1 } /* ReverseArray(new BigInteger((ulong)SignatureKey).GetBytes()) */);
            BigInteger mod = new BigInteger(ServerModulus, 16);
            BigInteger sig = new BigInteger(ReverseArray(serverSignature));

            byte[] result = sig.ModPow(key, mod).GetBytes();
            BigInteger res = new BigInteger(ReverseArray(result));

            MemoryStream ms_res = new MemoryStream(result.Length);
            ms_res.Write(ipAddress, 0, 4);
            for (int i = 4; i < result.Length; i++)
                ms_res.WriteByte(0xbb);

            ms_res.Seek(-1, SeekOrigin.Current);
            ms_res.WriteByte(0x0b);

            BigInteger cor_res = new BigInteger(ms_res.GetBuffer());
            ms_res.Close();

            return cor_res.Equals(res);
        }
Ejemplo n.º 30
0
		public virtual X509CrlEntry GetRevokedCertificate(
			BigInteger serialNumber)
		{
			IEnumerable certs = c.GetRevokedCertificateEnumeration();

			X509Name previousCertificateIssuer = IssuerDN;
			foreach (CrlEntry entry in certs)
			{
				X509CrlEntry crlEntry = new X509CrlEntry(entry, isIndirect, previousCertificateIssuer);

				if (serialNumber.Equals(entry.UserCertificate.Value))
				{
					return crlEntry;
				}

				previousCertificateIssuer = crlEntry.GetCertificateIssuer();
			}

			return null;
		}
Ejemplo n.º 31
0
        private static void VerifyComparison(BigInteger x, BigInteger y, int expectedResult)
        {
            bool expectedEquals = 0 == expectedResult;
            bool expectedLessThan = expectedResult < 0;
            bool expectedGreaterThan = expectedResult > 0;

            Assert.Equal(expectedEquals, x == y);
            Assert.Equal(expectedEquals, y == x);

            Assert.Equal(!expectedEquals, x != y);
            Assert.Equal(!expectedEquals, y != x);

            Assert.Equal(expectedEquals, x.Equals(y));
            Assert.Equal(expectedEquals, y.Equals(x));

            Assert.Equal(expectedEquals, x.Equals((Object)y));
            Assert.Equal(expectedEquals, y.Equals((Object)x));

            VerifyCompareResult(expectedResult, x.CompareTo(y), "x.CompareTo(y)");
            VerifyCompareResult(-expectedResult, y.CompareTo(x), "y.CompareTo(x)");

            IComparable comparableX = x;
            IComparable comparableY = y;
            VerifyCompareResult(expectedResult, comparableX.CompareTo(y), "comparableX.CompareTo(y)");
            VerifyCompareResult(-expectedResult, comparableY.CompareTo(x), "comparableY.CompareTo(x)");

            VerifyCompareResult(expectedResult, BigInteger.Compare(x, y), "Compare(x,y)");
            VerifyCompareResult(-expectedResult, BigInteger.Compare(y, x), "Compare(y,x)");

            if (expectedEquals)
            {
                Assert.Equal(x.GetHashCode(), y.GetHashCode());
                Assert.Equal(x.ToString(), y.ToString());
            }

            Assert.Equal(x.GetHashCode(), x.GetHashCode());
            Assert.Equal(y.GetHashCode(), y.GetHashCode());

            Assert.Equal(expectedLessThan, x < y);
            Assert.Equal(expectedGreaterThan, y < x);

            Assert.Equal(expectedGreaterThan, x > y);
            Assert.Equal(expectedLessThan, y > x);

            Assert.Equal(expectedLessThan || expectedEquals, x <= y);
            Assert.Equal(expectedGreaterThan || expectedEquals, y <= x);

            Assert.Equal(expectedGreaterThan || expectedEquals, x >= y);
            Assert.Equal(expectedLessThan || expectedEquals, y >= x);
        }
Ejemplo n.º 32
0
        private static void VerifyComparison(BigInteger x, bool IsXNegative, BigInteger y, bool IsYNegative, int expectedResult)
        {
            bool expectedEquals = 0 == expectedResult;
            bool expectedLessThan = expectedResult < 0;
            bool expectedGreaterThan = expectedResult > 0;

            if (IsXNegative == true)
            {
                x = x * -1;
            }
            if (IsYNegative == true)
            {
                y = y * -1;
            }

            Assert.Equal(expectedEquals, x == y);
            Assert.Equal(expectedEquals, y == x);

            Assert.Equal(!expectedEquals, x != y);
            Assert.Equal(!expectedEquals, y != x);

            Assert.Equal(expectedEquals, x.Equals(y));
            Assert.Equal(expectedEquals, y.Equals(x));

            Assert.Equal(expectedEquals, x.Equals((Object)y));
            Assert.Equal(expectedEquals, y.Equals((Object)x));

            VerifyCompareResult(expectedResult, x.CompareTo(y), "x.CompareTo(y)");
            VerifyCompareResult(-expectedResult, y.CompareTo(x), "y.CompareTo(x)");

            if (expectedEquals)
            {
                Assert.Equal(x.GetHashCode(), y.GetHashCode());
                Assert.Equal(x.ToString(), y.ToString());
            }

            Assert.Equal(x.GetHashCode(), x.GetHashCode());
            Assert.Equal(y.GetHashCode(), y.GetHashCode());

            Assert.Equal(expectedLessThan, x < y);
            Assert.Equal(expectedGreaterThan, y < x);

            Assert.Equal(expectedGreaterThan, x > y);
            Assert.Equal(expectedLessThan, y > x);

            Assert.Equal(expectedLessThan || expectedEquals, x <= y);
            Assert.Equal(expectedGreaterThan || expectedEquals, y <= x);

            Assert.Equal(expectedGreaterThan || expectedEquals, x >= y);
            Assert.Equal(expectedLessThan || expectedEquals, y >= x);
        }
Ejemplo n.º 33
0
 public void Equals_BI_on_null_is_false()
 {
     BigInteger i = new BigInteger(1, 0x1, 0x2, 0x3);
     Expect(i.Equals(null), False);
 }
Ejemplo n.º 34
0
        private void MultiplyOverField(int blockSizeBits, byte[] x, byte[] y, byte[] x_mult_y)
        {
            //Multiplication over GF(2^m), GF(2^256), GF(2^512) with correspondent extension polynomials:
            ///
            /// GF(2^128) | x^128 + x^7 + x^2 + x
            /// GF(2^256) | x^256 + x^10 + x^5 + x^2 + 1
            /// GF(2^512) | x^512 + x^8 + x^5 + x^2 + 1
            ///
            //Thanks to João H de A Franco script. https://jhafranco.com/2012/02/17/multiplication-over-the-binary-finite-field-gf2m/

            byte[] copy1 = new byte[cipher.GetBlockSize()];
            byte[] copy2 = new byte[cipher.GetBlockSize()];

            Array.Copy(x, 0, copy1, 0, cipher.GetBlockSize());
            Array.Copy(y, 0, copy2, 0, cipher.GetBlockSize());


            Array.Reverse(copy1);
            Array.Reverse(copy2);


            BigInteger mask1;
            BigInteger mask2;
            BigInteger polyred;

            switch (blockSizeBits)
            {
            case 128:
                mask1   = mask1_128;
                mask2   = mask2_128;
                polyred = polyred_128;
                break;

            case 256:
                mask1   = mask1_256;
                mask2   = mask2_256;
                polyred = polyred_256;
                break;

            case 512:
                mask1   = mask1_512;
                mask2   = mask2_512;
                polyred = polyred_512;
                break;

            default:
                mask1   = mask1_128;
                mask2   = mask2_128;
                polyred = polyred_128;
                break;
            }

            BigInteger p  = BigInteger.Zero;
            BigInteger p1 = new BigInteger(1, copy1);
            BigInteger p2 = new BigInteger(1, copy2);

            while (!p2.Equals(BigInteger.Zero))
            {
                if (p2.And(BigInteger.One).Equals(BigInteger.One))
                {
                    p = p.Xor(p1);
                }

                p1 = p1.ShiftLeft(1);

                if (!p1.And(mask1).Equals(BigInteger.Zero))
                {
                    p1 = p1.Xor(polyred);
                }

                p2 = p2.ShiftRight(1);
            }

            byte[] got = p.And(mask2).ToByteArrayUnsigned();

            Array.Clear(x_mult_y, 0, cipher.GetBlockSize());

            Array.Copy(got, 0, x_mult_y, 0, got.Length);
        }
Ejemplo n.º 35
0
        public static object BIDivide(BigInteger n, BigInteger d)
        {
            if (d.Equals(BigInteger.ZERO))
                throw new ArithmeticException("Divide by zero");
            //BigInteger gcd = n.gcd(d);
            BigInteger gcd = n.Gcd(d);
            if (gcd.Equals(BigInteger.ZERO))
                return 0;
            //n = n.divide(gcd);
            //d = d.divide(gcd);
            n = n / gcd;
            d = d / gcd;

            if (d.Equals(BigInteger.ONE))
                return reduce(n);
            //return new Ratio((d.signum() < 0 ? n.negate() : n),
            //    (d.signum() < 0 ? d.negate() : d));
            return new Ratio((d.Signum < 0 ? -n : n), d.Abs());
        }
Ejemplo n.º 36
0
 protected bool Equals(
     FpCurve other)
 {
     return(base.Equals(other) && q.Equals(other.q));
 }
Ejemplo n.º 37
0
 protected bool Equals(
     DsaPublicKeyParameters other)
 {
     return(y.Equals(other.y) && base.Equals(other));
 }
Ejemplo n.º 38
0
 public void ConstructorBytes()
 {
     var myByteArray = new byte[] { (byte)0x00, (byte)0xFF, (byte)0xFE };
     bi = new BigInteger(myByteArray);
     Assert.IsTrue(bi.Equals(BigInteger.Zero.SetBit(16).Subtract(two)), "Incorrect value for pos number");
     myByteArray = new byte[] { (byte)0xFF, (byte)0xFE };
     bi = new BigInteger(myByteArray);
     Assert.IsTrue(bi.Equals(minusTwo), "Incorrect value for neg number");
 }
Ejemplo n.º 39
0
        /// <summary>
        /// Computes the value of the Jacobi symbol (A|B). 
        /// </summary>
        /// 
        /// <param name="A">The integer value</param>
        /// <param name="B">The integer value</param>
        /// 
        /// <returns>Returns value of the jacobi symbol (A|B)</returns>
        public static int Jacobi(BigInteger A, BigInteger B)
        {
            BigInteger a, b, v;
            long k = 1;

            // test trivial cases
            if (B.Equals(ZERO))
            {
                a = A.Abs();
                return a.Equals(ONE) ? 1 : 0;
            }

            if (!A.TestBit(0) && !B.TestBit(0))
                return 0;

            a = A;
            b = B;

            if (b.Signum() == -1)
            { // b < 0
                b = b.Negate();
                if (a.Signum() == -1)
                    k = -1;
            }

            v = ZERO;
            while (!b.TestBit(0))
            {
                v = v.Add(ONE);
                b = b.Divide(TWO);
            }

            if (v.TestBit(0))
                k = k * _jacobiTable[a.ToInt32() & 7];

            if (a.Signum() < 0)
            {
                if (b.TestBit(1))
                    k = -k;
                a = a.Negate();
            }

            // main loop
            while (a.Signum() != 0)
            {
                v = ZERO;
                while (!a.TestBit(0))
                { // a is even
                    v = v.Add(ONE);
                    a = a.Divide(TWO);
                }
                if (v.TestBit(0))
                    k = k * _jacobiTable[b.ToInt32() & 7];

                if (a.CompareTo(b) < 0)
                {
                    // swap and correct intermediate result
                    BigInteger x = a;
                    a = b;
                    b = x;
                    if (a.TestBit(1) && b.TestBit(1))
                        k = -k;
                }
                a = a.Subtract(b);
            }

            return b.Equals(ONE) ? (int)k : 0;
        }
Ejemplo n.º 40
0
        public void ConstructorIBytes()
        {
            var myByteArray = new byte[] { (byte)0xFF, (byte)0xFE };
            bi = new BigInteger(1, myByteArray);
            Assert.IsTrue(bi.Equals(BigInteger.Zero.SetBit(16).Subtract(two)), "Incorrect value for pos number");
            bi = new BigInteger(-1, myByteArray);
            Assert.IsTrue(bi.Equals(BigInteger.Zero.SetBit(16).Subtract(two).Negate()), "Incorrect value for neg number");
            myByteArray = new byte[] { (byte)0, (byte)0 };
            bi = new BigInteger(0, myByteArray);
            Assert.IsTrue(bi.Equals(zero), "Incorrect value for zero");
            myByteArray = new byte[] { (byte)1 };

            Assert.Throws<FormatException>(() => new BigInteger(0, myByteArray));
        }
Ejemplo n.º 41
0
        private static void VerifyComparison(BigInteger x, UInt64 y, int expectedResult)
        {
            bool expectedEquals = 0 == expectedResult;
            bool expectedLessThan = expectedResult < 0;
            bool expectedGreaterThan = expectedResult > 0;

            Assert.Equal(expectedEquals, x == y);
            Assert.Equal(expectedEquals, y == x);

            Assert.Equal(!expectedEquals, x != y);
            Assert.Equal(!expectedEquals, y != x);

            Assert.Equal(expectedEquals, x.Equals(y));

            VerifyCompareResult(expectedResult, x.CompareTo(y), "x.CompareTo(y)");

            if (expectedEquals)
            {
                Assert.Equal(x.GetHashCode(), ((BigInteger)y).GetHashCode());
                Assert.Equal(x.ToString(), ((BigInteger)y).ToString());
            }

            Assert.Equal(x.GetHashCode(), x.GetHashCode());
            Assert.Equal(((BigInteger)y).GetHashCode(), ((BigInteger)y).GetHashCode());

            Assert.Equal(expectedLessThan, x < y);
            Assert.Equal(expectedGreaterThan, y < x);

            Assert.Equal(expectedGreaterThan, x > y);
            Assert.Equal(expectedLessThan, y > x);

            Assert.Equal(expectedLessThan || expectedEquals, x <= y);
            Assert.Equal(expectedGreaterThan || expectedEquals, y <= x);

            Assert.Equal(expectedGreaterThan || expectedEquals, x >= y);
            Assert.Equal(expectedLessThan || expectedEquals, y >= x);
        }
Ejemplo n.º 42
0
        /**
         * return a sqrt root - the routine verifies that the calculation
         * returns the right value - if none exists it returns null.
         */
        public override ECFieldElement Sqrt()
        {
            if (IsZero || IsOne)
            {
                return(this);
            }

            if (!q.TestBit(0))
            {
                throw Platform.CreateNotImplementedException("even value of q");
            }

            if (q.TestBit(1))            // q == 4m + 3
            {
                BigInteger e = q.ShiftRight(2).Add(BigInteger.One);
                return(CheckSqrt(new FpFieldElement(q, r, x.ModPow(e, q))));
            }

            if (q.TestBit(2))            // q == 8m + 5
            {
                BigInteger t1 = x.ModPow(q.ShiftRight(3), q);
                BigInteger t2 = ModMult(t1, x);
                BigInteger t3 = ModMult(t2, t1);

                if (t3.Equals(BigInteger.One))
                {
                    return(CheckSqrt(new FpFieldElement(q, r, t2)));
                }

                // TODO This is constant and could be precomputed
                BigInteger t4 = BigInteger.Two.ModPow(q.ShiftRight(2), q);

                BigInteger y = ModMult(t2, t4);

                return(CheckSqrt(new FpFieldElement(q, r, y)));
            }

            // q == 8m + 1

            BigInteger legendreExponent = q.ShiftRight(1);

            if (!(x.ModPow(legendreExponent, q).Equals(BigInteger.One)))
            {
                return(null);
            }

            BigInteger X     = this.x;
            BigInteger fourX = ModDouble(ModDouble(X));

            ;

            BigInteger k = legendreExponent.Add(BigInteger.One), qMinusOne = q.Subtract(BigInteger.One);

            BigInteger U, V;

            do
            {
                BigInteger P;
                do
                {
                    P = BigInteger.Arbitrary(q.BitLength);
                }while(P.CompareTo(q) >= 0 ||
                       !ModReduce(P.Multiply(P).Subtract(fourX)).ModPow(legendreExponent, q).Equals(qMinusOne));

                BigInteger[] result = LucasSequence(P, X, k);
                U = result[0];
                V = result[1];

                if (ModMult(V, V).Equals(fourX))
                {
                    return(new FpFieldElement(q, r, ModHalfAbs(V)));
                }
            }while(U.Equals(BigInteger.One) || U.Equals(qMinusOne));

            return(null);
        }
Ejemplo n.º 43
0
        public static object BIDivide(BigInteger n, BigInteger d)
        {
            if (d.Equals(BigInteger.ZERO))
                throw new ArithmeticException("Divide by zero");
            BigInteger gcd = n.Gcd(d);
            if (gcd.Equals(BigInteger.ZERO))
                return BigInt.ZERO;
            n = n / gcd;
            d = d / gcd;

            if (d.Equals(BigInteger.ONE))
                return BigInt.fromBigInteger(n);
            else if (d.Equals(BigInteger.NEGATIVE_ONE))
                return BigInt.fromBigInteger(n.Negate());

            return new Ratio((d.Signum < 0 ? -n : n), d.Abs());
        }
Ejemplo n.º 44
0
 public void EqualsTest3()
 {
     BigInteger target = new BigInteger(); // TODO: Initialize to an appropriate value
     long other = 0; // TODO: Initialize to an appropriate value
     bool expected = false; // TODO: Initialize to an appropriate value
     bool actual;
     actual = target.Equals(other);
     Assert.AreEqual(expected, actual);
     Assert.Inconclusive("Verify the correctness of this test method.");
 }