Subtract() public méthode

public Subtract ( BigInteger n ) : BigInteger
n BigInteger
Résultat BigInteger
        /// <summary>Choose a random prime value for use with RSA</summary>
        /// <param name="bitlength">the bit-length of the returned prime</param>
        /// <param name="e">the RSA public exponent</param>
        /// <returns>a prime p, with (p-1) relatively prime to e</returns>
        protected virtual BigInteger ChooseRandomPrime(int bitlength, BigInteger e)
        {
            for (;;)
            {
                BigInteger p = new BigInteger(bitlength, 1, param.Random);

                if (p.Mod(e).Equals(BigInteger.One))
                    continue;

                if (!p.IsProbablePrime(param.Certainty))
                    continue;

                if (!e.Gcd(p.Subtract(BigInteger.One)).Equals(BigInteger.One))
                    continue;

                return p;
            }
        }
		public AsymmetricCipherKeyPair GenerateKeyPair()
        {
            BigInteger p, q, n, d, e, pSub1, qSub1, phi;

            //
            // p and q values should have a length of half the strength in bits
            //
			int strength = param.Strength;
            int pbitlength = (strength + 1) / 2;
            int qbitlength = (strength - pbitlength);
			int mindiffbits = strength / 3;

			e = param.PublicExponent;

			// TODO Consider generating safe primes for p, q (see DHParametersHelper.generateSafePrimes)
			// (then p-1 and q-1 will not consist of only small factors - see "Pollard's algorithm")

			//
            // Generate p, prime and (p-1) relatively prime to e
            //
            for (;;)
            {
				p = new BigInteger(pbitlength, 1, param.Random);

				if (p.Mod(e).Equals(BigInteger.One))
					continue;

				if (!p.IsProbablePrime(param.Certainty))
					continue;

				if (e.Gcd(p.Subtract(BigInteger.One)).Equals(BigInteger.One)) 
					break;
			}

            //
            // Generate a modulus of the required length
            //
            for (;;)
            {
                // Generate q, prime and (q-1) relatively prime to e,
                // and not equal to p
                //
                for (;;)
                {
					q = new BigInteger(qbitlength, 1, param.Random);

					if (q.Subtract(p).Abs().BitLength < mindiffbits)
						continue;

					if (q.Mod(e).Equals(BigInteger.One))
						continue;

					if (!q.IsProbablePrime(param.Certainty))
						continue;

					if (e.Gcd(q.Subtract(BigInteger.One)).Equals(BigInteger.One)) 
						break;
				}

                //
                // calculate the modulus
                //
                n = p.Multiply(q);

                if (n.BitLength == param.Strength)
					break;

                //
                // if we Get here our primes aren't big enough, make the largest
                // of the two p and try again
                //
                p = p.Max(q);
            }

			if (p.CompareTo(q) < 0)
			{
				phi = p;
				p = q;
				q = phi;
			}

            pSub1 = p.Subtract(BigInteger.One);
            qSub1 = q.Subtract(BigInteger.One);
            phi = pSub1.Multiply(qSub1);

            //
            // calculate the private exponent
            //
            d = e.ModInverse(phi);

            //
            // calculate the CRT factors
            //
            BigInteger dP, dQ, qInv;

            dP = d.Remainder(pSub1);
            dQ = d.Remainder(qSub1);
            qInv = q.ModInverse(p);

            return new AsymmetricCipherKeyPair(
                new RsaKeyParameters(false, n, e),
                new RsaPrivateCrtKeyParameters(n, e, d, p, q, dP, dQ, qInv));
        }
		/**
		* Return a random BigInteger not less than 'min' and not greater than 'max'
		* 
		* @param min the least value that may be generated
		* @param max the greatest value that may be generated
		* @param random the source of randomness
		* @return a random BigInteger value in the range [min,max]
		*/
		public static BigInteger CreateRandomInRange(
			BigInteger		min,
			BigInteger		max,
			// TODO Should have been just Random class
			SecureRandom	random)
		{
			int cmp = min.CompareTo(max);
			if (cmp >= 0)
			{
				if (cmp > 0)
					throw new ArgumentException("'min' may not be greater than 'max'");

				return min;
			}

			if (min.BitLength > max.BitLength / 2)
			{
				return CreateRandomInRange(BigInteger.Zero, max.Subtract(min), random).Add(min);
			}

			for (int i = 0; i < MaxIterations; ++i)
			{
				BigInteger x = new BigInteger(max.BitLength, random);
				if (x.CompareTo(min) >= 0 && x.CompareTo(max) <= 0)
				{
					return x;
				}
			}

			// fall back to a faster (restricted) method
			return new BigInteger(max.Subtract(min).BitLength - 1, random).Add(min);
		}
        /// <summary>
        /// Constructor used by the pre-approved groups in JPakePrimeOrderGroups.
        /// These pre-approved groups can avoid the expensive checks.
        /// User-specified groups should not use this constructor.
        /// </summary>
        public JPakePrimeOrderGroup(BigInteger p, BigInteger q, BigInteger g, bool skipChecks)
        {
            JPakeUtilities.ValidateNotNull(p, "p");
            JPakeUtilities.ValidateNotNull(q, "q");
            JPakeUtilities.ValidateNotNull(g, "g");

            if (!skipChecks)
            {
                if (!p.Subtract(JPakeUtilities.One).Mod(q).Equals(JPakeUtilities.Zero))
                    throw new ArgumentException("p-1 must be evenly divisible by q");
                if (g.CompareTo(BigInteger.Two) == -1 || g.CompareTo(p.Subtract(JPakeUtilities.One)) == 1)
                    throw new ArgumentException("g must be in [2, p-1]");
                if (!g.ModPow(q, p).Equals(JPakeUtilities.One))
                    throw new ArgumentException("g^q mod p must equal 1");

                // Note these checks do not guarantee that p and q are prime.
                // We just have reasonable certainty that they are prime.
                if (!p.IsProbablePrime(20))
                    throw new ArgumentException("p must be prime");
                if (!q.IsProbablePrime(20))
                    throw new ArgumentException("q must be prime");
            }

            this.p = p;
            this.q = q;
            this.g = g;
        }
		public RsaSecretBcpgKey(
			BigInteger d,
			BigInteger p,
			BigInteger q)
		{
			// PGP requires (p < q)
			int cmp = p.CompareTo(q);
			if (cmp >= 0)
			{
				if (cmp == 0)
					throw new ArgumentException("p and q cannot be equal");

				BigInteger tmp = p;
				p = q;
				q = tmp;
			}

			this.d = new MPInteger(d);
			this.p = new MPInteger(p);
			this.q = new MPInteger(q);
			this.u = new MPInteger(p.ModInverse(q));

			this.expP = d.Remainder(p.Subtract(BigInteger.One));
			this.expQ = d.Remainder(q.Subtract(BigInteger.One));
			this.crt = q.ModInverse(p);
		}
Exemple #6
0
        public RSA(int bits)
        {
            p = Helper.GenerateBigIntegerPrimes(bits);
            //p = new Org.BouncyCastle.Math.BigInteger("3557");
            q = Helper.GenerateBigIntegerPrimes(bits);
            //q = new Org.BouncyCastle.Math.BigInteger("2579");
            Console.WriteLine("p generated " + p);
            Console.WriteLine("q generated " + q);
            n = p.Multiply(q);
            Console.WriteLine("n = " + n);
            BigInteger p1 = p.Subtract(new BigInteger("1"));
            BigInteger q1 = q.Subtract(new BigInteger("1"));

            fn = p1.Multiply(q1);
            Console.WriteLine("Функция Эйлера = " + fn);
            int[]  er   = new[] { 17, 257, 65537 };
            Random rand = new Random((int)System.DateTime.Now.Ticks);

            e = new BigInteger(er[rand.Next(0, er.Length)].ToString());
            Console.WriteLine("e = " + e);

            d = e.ModInverse(fn);
            Console.WriteLine("d = " + d);

            Console.WriteLine("Public Key: " + e + ", " + n);
            Console.WriteLine("Private Key: " + d + ", " + n);
        }
        internal BigInteger CalculatePrivate(
			BigInteger		p,
			SecureRandom	random,
			int				limit)
        {
            //
            // calculate the private key
            //
            BigInteger pSub2 = p.Subtract(BigInteger.Two);
            BigInteger x;

            if (limit == 0)
            {
                x = createInRange(pSub2, random);
            }
            else
            {
                do
                {
                    // TODO Check this (should the generated numbers always be odd,
                    // and length 'limit'?)
                    x = new BigInteger(limit, 0, random);
                }
                while (x.SignValue == 0);
            }

            return x;
        }
		public static BigInteger GeneratePrivateValue(IDigest digest, BigInteger N, BigInteger g, SecureRandom random)
	    {
			int minBits = System.Math.Min(256, N.BitLength / 2);
	        BigInteger min = BigInteger.One.ShiftLeft(minBits - 1);
	        BigInteger max = N.Subtract(BigInteger.One);

	        return BigIntegers.CreateRandomInRange(min, max, random);
	    }
		private static BigInteger GeneratePrivateKey(BigInteger q, SecureRandom random)
		{
			// TODO Prefer this method? (change test cases that used fixed random)
			// B.1.1 Key Pair Generation Using Extra Random Bits
//	        BigInteger c = new BigInteger(q.BitLength + 64, random);
//	        return c.Mod(q.Subtract(BigInteger.One)).Add(BigInteger.One);

			// B.1.2 Key Pair Generation by Testing Candidates
			return BigIntegers.CreateRandomInRange(BigInteger.One, q.Subtract(BigInteger.One), random);
		}
Exemple #10
0
        public String decipher(List <Org.BouncyCastle.Math.BigInteger> cipher, MHPrivateKey key)
        {
            String decrypted = "";

            Org.BouncyCastle.Math.BigInteger temp = Org.BouncyCastle.Math.BigInteger.ValueOf(0);
            int tmp = 0;

            Org.BouncyCastle.Math.BigInteger bits = Org.BouncyCastle.Math.BigInteger.ValueOf(0);

            for (int i = 0; i < cipher.Count; i++)
            {
                temp = cipher.ElementAt(i);
                int bitlen = temp.BitLength;
                int ff     = 0;
                while (bitlen < (int)Math.Pow(2, ff))
                {
                    ff++;
                }
                if (ff > bitlen)
                {
                    bitlen = ff;
                }

                for (int j = 0; j < bitlen; j++)
                {
                    if (temp.Mod(Org.BouncyCastle.Math.BigInteger.ValueOf(2)).CompareTo(Org.BouncyCastle.Math.BigInteger.ValueOf(1)) == 0)
                    {
                        bits = bits.Add(key.w1.Multiply(Org.BouncyCastle.Math.BigInteger.ValueOf((long)Math.Pow(2, j))));
                    }
                    temp = temp.ShiftRight(1);
                }
                bits = bits.Mod(key.n);
                List <Org.BouncyCastle.Math.BigInteger> list = key.a;
                Org.BouncyCastle.Math.BigInteger        temper;

                int k = key.a.Count - 1;
                while (k >= 0)
                {
                    temper = list.ElementAt(k);
                    if (bits.CompareTo(temper) > -1)
                    {
                        tmp += (int)Math.Pow(2, k);
                        bits = bits.Subtract(temper);
                    }
                    k--;
                }
                decrypted += (binaryToChar(Convert.ToString(tmp, 2))).ToString();

                bits = Org.BouncyCastle.Math.BigInteger.ValueOf(0);
                tmp  = 0;
            }
            return(decrypted);
        }
        private static BigInteger GeneratePrivateKey(BigInteger q, SecureRandom random)
        {
            // B.1.2 Key Pair Generation by Testing Candidates
            int minWeight = q.BitLength >> 2;
            for (;;)
            {
                // TODO Prefer this method? (change test cases that used fixed random)
                // B.1.1 Key Pair Generation Using Extra Random Bits
                //BigInteger x = new BigInteger(q.BitLength + 64, random).Mod(q.Subtract(One)).Add(One);

                BigInteger x = BigIntegers.CreateRandomInRange(One, q.Subtract(One), random);
                if (WNafUtilities.GetNafWeight(x) >= minWeight)
                {
                    return x;
                }
            }
        }
Exemple #12
0
		public DHParameters(
			BigInteger				p,
			BigInteger				g,
			BigInteger				q,
			int						m,
			int						l,
			BigInteger				j,
			DHValidationParameters	validation)
		{
			if (p == null)
				throw new ArgumentNullException("p");
			if (g == null)
				throw new ArgumentNullException("g");
			if (!p.TestBit(0))
				throw new ArgumentException("field must be an odd prime", "p");
			if (g.CompareTo(BigInteger.Two) < 0
				|| g.CompareTo(p.Subtract(BigInteger.Two)) > 0)
				throw new ArgumentException("generator must in the range [2, p - 2]", "g");
			if (q != null && q.BitLength >= p.BitLength)
				throw new ArgumentException("q too big to be a factor of (p-1)", "q");
			if (m >= p.BitLength)
				throw new ArgumentException("m value must be < bitlength of p", "m");
			if (l != 0)
			{ 
                // TODO Check this against the Java version, which has 'l > p.BitLength' here
	            if (l >= p.BitLength)
                	throw new ArgumentException("when l value specified, it must be less than bitlength(p)", "l");
				if (l < m)
					throw new ArgumentException("when l value specified, it may not be less than m value", "l");
			}
			if (j != null && j.CompareTo(BigInteger.Two) < 0)
				throw new ArgumentException("subgroup factor must be >= 2", "j");

			// TODO If q, j both provided, validate p = jq + 1 ?

			this.p = p;
			this.g = g;
			this.q = q;
			this.m = m;
			this.l = l;
			this.j = j;
			this.validation = validation;
        }
Exemple #13
0
 public static string Encode(byte[] input)
 {
     var bi = new BigInteger(1, input);
     var s = new StringBuilder();
     while (bi.CompareTo(Base) >= 0)
     {
         var mod = bi.Mod(Base);
         s.Insert(0, new[] {Alphabet[mod.IntValue]});
         bi = bi.Subtract(mod).Divide(Base);
     }
     s.Insert(0, new[] {Alphabet[bi.IntValue]});
     // Convert leading zeros too.
     foreach (var anInput in input)
     {
         if (anInput == 0)
             s.Insert(0, new[] {Alphabet[0]});
         else
             break;
     }
     return s.ToString();
 }
        public RsaSecretBcpgKey(
			BigInteger d,
			BigInteger p,
			BigInteger q)
        {
            // pgp requires (p < q)
            if (p.CompareTo(q) > 0)
            {
                BigInteger tmp = p;
                p = q;
                q = tmp;
            }

            this.d = new MPInteger(d);
            this.p = new MPInteger(p);
            this.q = new MPInteger(q);
            this.u = new MPInteger(p.ModInverse(q));
            this.expP = d.Remainder(p.Subtract(BigInteger.One));
            this.expQ = d.Remainder(q.Subtract(BigInteger.One));
            this.crt = q.ModInverse(p);
        }
 /// <summary>
 /// Encode a byte sequence as a base58-encoded string
 /// </summary>
 /// <param name="bytes">Byte sequence</param>
 /// <returns>Encoding result</returns>
 public static string Base58Encode(byte[] input)
 {
     // TODO: This could be a lot more efficient.
     var bi = new BigInteger(1, input);
     var s = new StringBuilder();
     while (bi.CompareTo(_base) >= 0)
     {
         var mod = bi.Mod(_base);
         s.Insert(0, new[] { strDigits[mod.IntValue] });
         bi = bi.Subtract(mod).Divide(_base);
     }
     s.Insert(0, new[] { strDigits[bi.IntValue] });
     // Convert leading zeros too.
     foreach (var anInput in input)
     {
         if (anInput == 0)
             s.Insert(0, new[] { strDigits[0] });
         else
             break;
     }
     return s.ToString();
 }
		private static BigInteger CalculateGenerator_FIPS186_3_Verifiable(IDigest d, BigInteger p, BigInteger q,
			byte[] seed, int index)
		{
			// A.2.3 Verifiable Canonical Generation of the Generator g
			BigInteger e = p.Subtract(BigInteger.One).Divide(q);
			byte[] ggen = Hex.Decode("6767656E");

			// 7. U = domain_parameter_seed || "ggen" || index || count.
			byte[] U = new byte[seed.Length + ggen.Length + 1 + 2];
			Array.Copy(seed, 0, U, 0, seed.Length);
			Array.Copy(ggen, 0, U, seed.Length, ggen.Length);
			U[U.Length - 3] = (byte)index; 

			byte[] w = new byte[d.GetDigestSize()];
			for (int count = 1; count < (1 << 16); ++count)
			{
				Inc(U);
				Hash(d, U, w);
				BigInteger W = new BigInteger(1, w);
				BigInteger g = W.ModPow(e, p);

				if (g.CompareTo(BigInteger.Two) >= 0)
					return g;
			}

			return null;
		}
		private static BigInteger CalculateGenerator_FIPS186_2(BigInteger p, BigInteger q, SecureRandom r)
		{
			BigInteger e = p.Subtract(BigInteger.One).Divide(q);
			BigInteger pSub2 = p.Subtract(BigInteger.Two);

			for (;;)
			{
				BigInteger h = BigIntegers.CreateRandomInRange(BigInteger.Two, pSub2, r);
				BigInteger g = h.ModPow(e, p);

				if (g.BitLength > 1)
					return g;
			}
		}
		/**
		 * Procedure C
		 * procedure generates the a value from the given p,q,
		 * returning the a value.
		 */
		private BigInteger procedure_C(BigInteger p, BigInteger q)
		{
			BigInteger pSub1 = p.Subtract(BigInteger.One);
			BigInteger pSub1Divq = pSub1.Divide(q);

			for(;;)
			{
				BigInteger d = new BigInteger(p.BitLength, init_random);

				// 1 < d < p-1
				if (d.CompareTo(BigInteger.One) > 0 && d.CompareTo(pSub1) < 0)
				{
					BigInteger a = d.ModPow(pSub1Divq, p);

					if (a.CompareTo(BigInteger.One) != 0)
					{
						return a;
					}
				}
			}
		}
Exemple #19
0
        private static BigInteger ReduceBarrett(BigInteger x, BigInteger m, BigInteger mr, BigInteger yu)
        {
            int xLen = x.BitLength, mLen = m.BitLength;
            if (xLen < mLen)
                return x;

            if (xLen - mLen > 1)
            {
                int k = m.magnitude.Length;

                BigInteger q1 = x.DivideWords(k - 1);
                BigInteger q2 = q1.Multiply(yu); // TODO Only need partial multiplication here
                BigInteger q3 = q2.DivideWords(k + 1);

                BigInteger r1 = x.RemainderWords(k + 1);
                BigInteger r2 = q3.Multiply(m); // TODO Only need partial multiplication here
                BigInteger r3 = r2.RemainderWords(k + 1);

                x = r1.Subtract(r3);
                if (x.sign < 0)
                {
                    x = x.Add(mr);
                }
            }

            while (x.CompareTo(m) >= 0)
            {
                x = x.Subtract(m);
            }

            return x;
        }
        /// <summary>Choose a random prime value for use with RSA</summary>
        /// <param name="bitlength">the bit-length of the returned prime</param>
        /// <param name="e">the RSA public exponent</param>
        /// <returns>a prime p, with (p-1) relatively prime to e</returns>
        protected virtual BigInteger ChooseRandomPrime(int bitlength, BigInteger e)
        {
            bool eIsKnownOddPrime = (e.BitLength <= SPECIAL_E_BITS) && Arrays.Contains(SPECIAL_E_VALUES, e.IntValue);

            for (;;)
            {
                BigInteger p = new BigInteger(bitlength, 1, parameters.Random);

                if (p.Mod(e).Equals(One))
                    continue;

                if (!p.IsProbablePrime(parameters.Certainty, true))
                    continue;

                if (!eIsKnownOddPrime && !e.Gcd(p.Subtract(One)).Equals(One))
                    continue;

                return p;
            }
        }
Exemple #21
0
		public BigInteger Add(
			BigInteger value)
		{
			if (this.sign == 0)
				return value;

			if (this.sign != value.sign)
			{
				if (value.sign == 0)
					return this;

				if (value.sign < 0)
					return Subtract(value.Negate());

				return value.Subtract(Negate());
			}

			return AddToMagnitude(value.magnitude);
		}
Exemple #22
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();
        }
 public BigInteger SolveRight(BigInteger[] pcs)
 {
     BigInteger accum = new BigInteger("0");
         foreach (coefficient c in rightside) {
             BigInteger scratch = new BigInteger(pcs[c.vindex].ToString());
             scratch = scratch.Multiply(new BigInteger(c.multiplier.ToString()));
             accum = accum.Add(scratch);
         }
         return accum.Subtract(subtractor).Divide(new BigInteger(divisor.ToString())); ;
 }
        /*
         * Select a high order element of the multiplicative group Zp*
         * 
         * p and q must be s.t. p = 2*q + 1, where p and q are prime (see generateSafePrimes)
         */
        internal static BigInteger SelectGenerator(BigInteger p, BigInteger q, SecureRandom random)
        {
            BigInteger pMinusTwo = p.Subtract(BigInteger.Two);
            BigInteger g;

            /*
             * (see: Handbook of Applied Cryptography 4.80)
             */
//			do
//			{
//				g = BigIntegers.CreateRandomInRange(BigInteger.Two, pMinusTwo, random);
//			}
//			while (g.ModPow(BigInteger.Two, p).Equals(BigInteger.One)
//				|| g.ModPow(q, p).Equals(BigInteger.One));

            /*
             * RFC 2631 2.2.1.2 (and see: Handbook of Applied Cryptography 4.81)
             */
            do
            {
                BigInteger h = BigIntegers.CreateRandomInRange(BigInteger.Two, pMinusTwo, random);

                g = h.ModPow(BigInteger.Two, p);
            }
            while (g.Equals(BigInteger.One));

            return g;
        }
		// Select a high order element of the multiplicative group Zp*
		// p and q must be s.t. p = 2*q + 1, where p and q are prime
		internal static BigInteger SelectGenerator(
			BigInteger      p,
			BigInteger      q,
			SecureRandom    random)
		{
			BigInteger pMinusTwo = p.Subtract(BigInteger.Two);
			BigInteger g;

			// Handbook of Applied Cryptography 4.86
			do
			{
				g = BigIntegers.CreateRandomInRange(BigInteger.Two, pMinusTwo, random);
			}
			while (g.ModPow(BigInteger.Two, p).Equals(BigInteger.One)
				|| g.ModPow(q, p).Equals(BigInteger.One));

/*
			// RFC 2631 2.1.1 (and see Handbook of Applied Cryptography 4.81)
			do
			{
				BigInteger h = CreateInRange(BigInteger.Two, pMinusTwo, random);

				g = h.ModPow(BigInteger.Two, p);
			}
			while (g.Equals(BigInteger.One));
*/

			return g;
		}
 /// <summary>
 /// Return a value that can be used as x2 or x4 during round 1.
 /// The returned value is a random value in the range [1, q-1].
 /// </summary>
 public static BigInteger GenerateX2(BigInteger q, SecureRandom random)
 {
     BigInteger min = One;
     BigInteger max = q.Subtract(One);
     return BigIntegers.CreateRandomInRange(min, max, random);
 }
		private DsaParameters GenerateParameters_FIPS186_2()
		{
            byte[] seed = new byte[20];
            byte[] part1 = new byte[20];
            byte[] part2 = new byte[20];
            byte[] u = new byte[20];
            Sha1Digest sha1 = new Sha1Digest();
			int n = (L - 1) / 160;
			byte[] w = new byte[L / 8];

			for (;;)
			{
				random.NextBytes(seed);

				Hash(sha1, seed, part1);
				Array.Copy(seed, 0, part2, 0, seed.Length);
				Inc(part2);
				Hash(sha1, part2, part2);

				for (int i = 0; i != u.Length; i++)
				{
					u[i] = (byte)(part1[i] ^ part2[i]);
				}

				u[0] |= (byte)0x80;
				u[19] |= (byte)0x01;

				BigInteger q = new BigInteger(1, u);

				if (!q.IsProbablePrime(certainty))
					continue;

				byte[] offset = Arrays.Clone(seed);
				Inc(offset);

				for (int counter = 0; counter < 4096; ++counter)
				{
					for (int k = 0; k < n; k++)
					{
						Inc(offset);
						Hash(sha1, offset, part1);
						Array.Copy(part1, 0, w, w.Length - (k + 1) * part1.Length, part1.Length);
					}

					Inc(offset);
					Hash(sha1, offset, part1);
					Array.Copy(part1, part1.Length - ((w.Length - (n) * part1.Length)), w, 0, w.Length - n * part1.Length);

					w[0] |= (byte)0x80;

					BigInteger x = new BigInteger(1, w);

					BigInteger c = x.Mod(q.ShiftLeft(1));

					BigInteger p = x.Subtract(c.Subtract(BigInteger.One));

					if (p.BitLength != L)
						continue;

					if (p.IsProbablePrime(certainty))
					{
						BigInteger g = CalculateGenerator_FIPS186_2(p, q, random);

						return new DsaParameters(p, q, g, new DsaValidationParameters(seed, counter));
					}
				}
			}
		}
Exemple #28
0
        /**
         * FIPS 186-4 C.3.1 Miller-Rabin Probabilistic Primality Test
         * 
         * Run several iterations of the Miller-Rabin algorithm with randomly-chosen bases.
         * 
         * @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 <code>false</code> if any witness to compositeness is found amongst the chosen bases
         *         (so <code>candidate</code> is definitely NOT prime), or else <code>true</code>
         *         (indicating primality with some probability dependent on the number of iterations
         *         that were performed).
         */
        public static bool IsMRProbablePrime(BigInteger candidate, SecureRandom random, int iterations)
        {
            CheckCandidate(candidate, "candidate");

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

            if (candidate.BitLength == 2)
                return true;
            if (!candidate.TestBit(0))
                return false;

            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);

                if (!ImplMRProbablePrimeToBase(w, wSubOne, m, a, b))
                    return false;
            }

            return true;
        }
Exemple #29
0
		// Section 7.2.6 ECVP-NR, pg 35
		/**
		 * return true if the value r and s represent a signature for the
		 * message passed in. Generally, the order of the curve should be at
		 * least as long as the hash of the message of interest, and with
		 * ECNR, it *must* be at least as long.  But just in case the signer
		 * applied mod(n) to the longer digest, this implementation will
		 * apply mod(n) during verification.
		 *
		 * @param digest  the digest to be verified.
		 * @param r       the r value of the signature.
		 * @param s       the s value of the signature.
		 * @exception DataLengthException if the digest is longer than the key allows
		 */
		public bool VerifySignature(
			byte[]		message,
			BigInteger	r,
			BigInteger	s)
		{
			if (this.forSigning)
			{
				// not properly initilaized... deal with it
				throw new InvalidOperationException("not initialised for verifying");
			}

			ECPublicKeyParameters pubKey = (ECPublicKeyParameters)key;
			BigInteger n = pubKey.Parameters.N;
			int nBitLength = n.BitLength;

			BigInteger e = new BigInteger(1, message);
			int eBitLength = e.BitLength;

			if (eBitLength > nBitLength)
			{
				throw new DataLengthException("input too large for ECNR key.");
			}

			// r in the range [1,n-1]
			if (r.CompareTo(BigInteger.One) < 0 || r.CompareTo(n) >= 0)
			{
				return false;
			}

			// TODO So why is this different from the spec?
			// s in the range [0,n-1]           NB: ECNR spec says 0
			if (s.CompareTo(BigInteger.Zero) < 0 || s.CompareTo(n) >= 0)
			{
				return false;
			}

			// compute P = sG + rW

			ECPoint G = pubKey.Parameters.G;
			ECPoint W = pubKey.Q;
			// calculate P using Bouncy math
			ECPoint P = ECAlgorithms.SumOfTwoMultiplies(G, s, W, r);

            if (P.IsInfinity)
                return false;

			BigInteger x = P.X.ToBigInteger();
			BigInteger t = r.Subtract(x).Mod(n);

			return t.Equals(e);
		}
Exemple #30
0
        /**
         * FIPS 186-4 C.3.1 Miller-Rabin Probabilistic Primality Test (to a fixed base).
         * 
         * Run a single iteration of the Miller-Rabin algorithm against the specified base.
         * 
         * @param candidate
         *            the {@link BigInteger} instance to test for primality.
         * @param baseValue
         *            the base value to use for this iteration.
         * @return <code>false</code> if the specified base is a witness to compositeness (so
         *         <code>candidate</code> is definitely NOT prime), or else <code>true</code>.
         */
        public static bool IsMRProbablePrimeToBase(BigInteger candidate, BigInteger baseValue)
        {
            CheckCandidate(candidate, "candidate");
            CheckCandidate(baseValue, "baseValue");

            if (baseValue.CompareTo(candidate.Subtract(One)) >= 0)
                throw new ArgumentException("must be < ('candidate' - 1)", "baseValue");

            if (candidate.BitLength == 2)
                return true;

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

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

            return ImplMRProbablePrimeToBase(w, wSubOne, m, a, baseValue);
        }
        /**
         * which Generates the p and g values from the given parameters,
         * returning the DsaParameters object.
         * <p>
         * Note: can take a while...</p>
         */
        public DsaParameters GenerateParameters()
        {
            byte[]          seed = new byte[20];
            byte[]          part1 = new byte[20];
            byte[]          part2 = new byte[20];
            byte[]          u = new byte[20];
            Sha1Digest      sha1 = new Sha1Digest();
            int             n = (size - 1) / 160;
            byte[]          w = new byte[size / 8];

            BigInteger      q = null, p = null, g = null;
            int             counter = 0;
            bool         primesFound = false;

            while (!primesFound)
            {
                do
                {
                    random.NextBytes(seed);

                    sha1.BlockUpdate(seed, 0, seed.Length);

                    sha1.DoFinal(part1, 0);

                    Array.Copy(seed, 0, part2, 0, seed.Length);

                    Add(part2, seed, 1);

                    sha1.BlockUpdate(part2, 0, part2.Length);

                    sha1.DoFinal(part2, 0);

                    for (int i = 0; i != u.Length; i++)
                    {
                        u[i] = (byte)(part1[i] ^ part2[i]);
                    }

                    u[0] |= (byte)0x80;
                    u[19] |= (byte)0x01;

                    q = new BigInteger(1, u);
                }
                while (!q.IsProbablePrime(certainty));

                counter = 0;

                int offset = 2;

                while (counter < 4096)
                {
                    for (int k = 0; k < n; k++)
                    {
                        Add(part1, seed, offset + k);
                        sha1.BlockUpdate(part1, 0, part1.Length);
                        sha1.DoFinal(part1, 0);
                        Array.Copy(part1, 0, w, w.Length - (k + 1) * part1.Length, part1.Length);
                    }

                    Add(part1, seed, offset + n);
                    sha1.BlockUpdate(part1, 0, part1.Length);
                    sha1.DoFinal(part1, 0);
                    Array.Copy(part1, part1.Length - ((w.Length - (n) * part1.Length)), w, 0, w.Length - n * part1.Length);

                    w[0] |= (byte)0x80;

                    BigInteger  x = new BigInteger(1, w);

                    BigInteger  c = x.Mod(q.ShiftLeft(1));

                    p = x.Subtract(c.Subtract(BigInteger.One));

                    if (p.TestBit(size - 1))
                    {
                        if (p.IsProbablePrime(certainty))
                        {
                            primesFound = true;
                            break;
                        }
                    }

                    counter += 1;
                    offset += n + 1;
                }
            }

            //
            // calculate the generator g
            //
            BigInteger  pMinusOneOverQ = p.Subtract(BigInteger.One).Divide(q);

            for (;;)
            {
                BigInteger h = new BigInteger(size, random);
                if (h.CompareTo(BigInteger.One) <= 0 || h.CompareTo(p.Subtract(BigInteger.One)) >= 0)
                {
                    continue;
                }

                g = h.ModPow(pMinusOneOverQ, p);
                if (g.CompareTo(BigInteger.One) <= 0)
                {
                    continue;
                }

                break;
            }

            return new DsaParameters(p, q, g, new DsaValidationParameters(seed, counter));
        }
        /// <summary>
        /// Calculate a zero knowledge proof of x using Schnorr's signature.
        /// The returned array has two elements {g^v, r = v-x*h} for x.
        /// </summary>
        public static BigInteger[] CalculateZeroKnowledgeProof(BigInteger p, BigInteger q, BigInteger g,
            BigInteger gx, BigInteger x, string participantId, IDigest digest, SecureRandom random)
        {
            /* Generate a random v, and compute g^v */
            BigInteger vMin = Zero;
            BigInteger vMax = q.Subtract(One);
            BigInteger v = BigIntegers.CreateRandomInRange(vMin, vMax, random);

            BigInteger gv = g.ModPow(v, p);
            BigInteger h = CalculateHashForZeroKnowledgeProof(g, gv, gx, participantId, digest); // h

            return new BigInteger[]
            {
                gv,
                v.Subtract(x.Multiply(h)).Mod(q) // r = v-x*h
            };
        }