Example #1
0
        /// <summary>
        ///     Create a new elliptic curve keypair.
        /// </summary>
        /// <param name="domain">Elliptic curve to use as the basis.</param>
        /// <param name="Q">Raw public key component.</param>
        /// <param name="d">Raw private key component.</param>
        /// <returns>Elliptic curve keypair.</returns>
        public static void GenerateECKeypair(ECDomainParameters domain, out ECPoint Q, out BigInteger d)
        {
            ECPoint    g         = domain.G;
            BigInteger n         = domain.N;
            int        minWeight = n.BitLength >> 2;

            for (;;)
            {
                d = new BigInteger(n.BitLength, StratCom.EntropySupplier);

                if (d.CompareTo(BigInteger.Two) < 0 || d.CompareTo(n) >= 0)
                {
                    continue;
                }

                /*
                 * Require a minimum weight of the NAF representation, since low-weight primes may be
                 * weak against a version of the number-field-sieve for the discrete-logarithm-problem.
                 *
                 * See "The number field sieve for integers of low weight", Oliver Schirokauer.
                 */
                if (WNafUtilities.GetNafWeight(d) < minWeight)
                {
                    continue;
                }

                break;
            }

            Q = EcBasePointMultiplier.Multiply(g, d);
        }
        public AsymmetricCipherKeyPair GenerateKeyPair()
        {
            BigInteger n = parameters.N;
            BigInteger d;
            int        minWeight = n.BitLength >> 2;

            for (;;)
            {
                d = new BigInteger(n.BitLength, random);

                if (d.CompareTo(BigInteger.Two) < 0 || d.CompareTo(n) >= 0)
                {
                    continue;
                }

                if (WNafUtilities.GetNafWeight(d) < minWeight)
                {
                    continue;
                }

                break;
            }

            ECPoint q = CreateBasePointMultiplier().Multiply(parameters.G, d);

            return(new AsymmetricCipherKeyPair(
                       new ECPublicKeyParameters(algorithm, q, parameters),
                       new ECPrivateKeyParameters(algorithm, d, parameters)));
        }
Example #3
0
        public virtual AsymmetricCipherKeyPair GenerateKeyPair()
        {
            int        num2;
            BigInteger publicExponent;
            BigInteger bigInteger;
            BigInteger bigInteger2;
            BigInteger bigInteger4;
            BigInteger bigInteger6;
            BigInteger bigInteger7;
            BigInteger bigInteger8;

            do
            {
                int strength = parameters.Strength;
                int num      = (strength + 1) / 2;
                num2 = strength - num;
                int num3 = strength / 3;
                int num4 = strength >> 2;
                publicExponent = parameters.PublicExponent;
                bigInteger     = ChooseRandomPrime(num, publicExponent);
                while (true)
                {
                    bigInteger2 = ChooseRandomPrime(num2, publicExponent);
                    BigInteger bigInteger3 = bigInteger2.Subtract(bigInteger).Abs();
                    if (bigInteger3.BitLength >= num3)
                    {
                        bigInteger4 = bigInteger.Multiply(bigInteger2);
                        if (bigInteger4.BitLength != strength)
                        {
                            bigInteger = bigInteger.Max(bigInteger2);
                        }
                        else
                        {
                            if (WNafUtilities.GetNafWeight(bigInteger4) >= num4)
                            {
                                break;
                            }
                            bigInteger = ChooseRandomPrime(num, publicExponent);
                        }
                    }
                }
                if (bigInteger.CompareTo(bigInteger2) < 0)
                {
                    BigInteger bigInteger5 = bigInteger;
                    bigInteger  = bigInteger2;
                    bigInteger2 = bigInteger5;
                }
                bigInteger6 = bigInteger.Subtract(One);
                bigInteger7 = bigInteger2.Subtract(One);
                BigInteger val = bigInteger6.Gcd(bigInteger7);
                BigInteger m   = bigInteger6.Divide(val).Multiply(bigInteger7);
                bigInteger8 = publicExponent.ModInverse(m);
            }while (bigInteger8.BitLength <= num2);
            BigInteger dP   = bigInteger8.Remainder(bigInteger6);
            BigInteger dQ   = bigInteger8.Remainder(bigInteger7);
            BigInteger qInv = bigInteger2.ModInverse(bigInteger);

            return(new AsymmetricCipherKeyPair(new RsaKeyParameters(isPrivate: false, bigInteger4, publicExponent), new RsaPrivateCrtKeyParameters(bigInteger4, publicExponent, bigInteger8, bigInteger, bigInteger2, dP, dQ, qInv)));
        }
Example #4
0
        private static BigInteger GeneratePrivateKey(BigInteger q, SecureRandom random)
        {
            int        num = q.BitLength >> 2;
            BigInteger bigInteger;

            do
            {
                bigInteger = BigIntegers.CreateRandomInRange(DsaKeyPairGenerator.One, q.Subtract(DsaKeyPairGenerator.One), random);
            }while (WNafUtilities.GetNafWeight(bigInteger) < num);
            return(bigInteger);
        }
        public virtual AsymmetricCipherKeyPair GenerateKeyPair()
        {
            int        num;
            BigInteger integer3;

Label_0005:
            num = this.parameters.Strength;
            int        bitlength      = (num + 1) / 2;
            int        num3           = num - bitlength;
            int        num4           = num / 3;
            int        num5           = num >> 2;
            BigInteger publicExponent = this.parameters.PublicExponent;
            BigInteger n = this.ChooseRandomPrime(bitlength, publicExponent);

Label_0041:
            integer3 = this.ChooseRandomPrime(num3, publicExponent);
            if (integer3.Subtract(n).Abs().BitLength < num4)
            {
                goto Label_0041;
            }
            BigInteger k = n.Multiply(integer3);

            if (k.BitLength != num)
            {
                n = n.Max(integer3);
                goto Label_0041;
            }
            if (WNafUtilities.GetNafWeight(k) < num5)
            {
                n = this.ChooseRandomPrime(bitlength, publicExponent);
                goto Label_0041;
            }
            if (n.CompareTo(integer3) < 0)
            {
                BigInteger integer6 = n;
                n        = integer3;
                integer3 = integer6;
            }
            BigInteger integer7        = n.Subtract(One);
            BigInteger integer8        = integer3.Subtract(One);
            BigInteger val             = integer7.Gcd(integer8);
            BigInteger m               = integer7.Divide(val).Multiply(integer8);
            BigInteger privateExponent = publicExponent.ModInverse(m);

            if (privateExponent.BitLength <= num3)
            {
                goto Label_0005;
            }
            BigInteger dP   = privateExponent.Remainder(integer7);
            BigInteger dQ   = privateExponent.Remainder(integer8);
            BigInteger qInv = integer3.ModInverse(n);

            return(new AsymmetricCipherKeyPair(new RsaKeyParameters(false, k, publicExponent), new RsaPrivateCrtKeyParameters(k, publicExponent, privateExponent, n, integer3, dP, dQ, qInv)));
        }
Example #6
0
        private static BigInteger GeneratePrivateKey(BigInteger q, SecureRandom random)
        {
            BigInteger integer;
            int        num = q.BitLength >> 2;

            do
            {
                integer = BigIntegers.CreateRandomInRange(One, q.Subtract(One), random);
            }while (WNafUtilities.GetNafWeight(integer) < num);
            return(integer);
        }
        public AsymmetricCipherKeyPair GenerateKeyPair()
        {
            SecureRandom       random         = param.Random;
            Gost3410Parameters gost3410Params = param.Parameters;

            BigInteger q = gost3410Params.Q, x;

            int minWeight = 64;

            for (;;)
            {
                x = new BigInteger(256, random);

                if (x.SignValue < 1 || x.CompareTo(q) >= 0)
                {
                    continue;
                }

                /*
                 * Require a minimum weight of the NAF representation, since low-weight primes may be
                 * weak against a version of the number-field-sieve for the discrete-logarithm-problem.
                 *
                 * See "The number field sieve for integers of low weight", Oliver Schirokauer.
                 */
                if (WNafUtilities.GetNafWeight(x) < minWeight)
                {
                    continue;
                }

                break;
            }

            BigInteger p = gost3410Params.P;
            BigInteger a = gost3410Params.A;

            // calculate the public key.
            BigInteger y = a.ModPow(x, p);

            if (param.PublicKeyParamSet != null)
            {
                return(new AsymmetricCipherKeyPair(
                           new Gost3410PublicKeyParameters(y, param.PublicKeyParamSet),
                           new Gost3410PrivateKeyParameters(x, param.PublicKeyParamSet)));
            }

            return(new AsymmetricCipherKeyPair(
                       new Gost3410PublicKeyParameters(y, gost3410Params),
                       new Gost3410PrivateKeyParameters(x, gost3410Params)));
        }
Example #8
0
        internal BigInteger CalculatePrivate(
            DHParameters dhParams,
            SecureRandom random)
        {
            int limit = dhParams.L;

            if (limit != 0)
            {
                int minWeight = limit >> 2;
                for (;;)
                {
                    BigInteger x = new BigInteger(limit, random).SetBit(limit - 1);
                    if (WNafUtilities.GetNafWeight(x) >= minWeight)
                    {
                        return(x);
                    }
                }
            }

            BigInteger min = BigInteger.Two;
            int        m   = dhParams.M;

            if (m != 0)
            {
                min = BigInteger.One.ShiftLeft(m - 1);
            }

            BigInteger q = dhParams.Q;

            if (q == null)
            {
                q = dhParams.P;
            }
            BigInteger max = q.Subtract(BigInteger.Two);

            {
                int minWeight = max.BitLength >> 2;
                for (;;)
                {
                    BigInteger x = BigIntegers.CreateRandomInRange(min, max, random);
                    if (WNafUtilities.GetNafWeight(x) >= minWeight)
                    {
                        return(x);
                    }
                }
            }
        }
Example #9
0
        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;
                }
            }
        }
Example #10
0
        public AsymmetricCipherKeyPair GenerateKeyPair()
        {
            SecureRandom       random         = param.Random;
            Gost3410Parameters gost3410Params = param.Parameters;

            BigInteger q = gost3410Params.Q, x;

            int minWeight = 64;

            for (;;)
            {
                x = new BigInteger(256, random);

                if (x.SignValue < 1 || x.CompareTo(q) >= 0)
                {
                    continue;
                }

                if (WNafUtilities.GetNafWeight(x) < minWeight)
                {
                    continue;
                }

                break;
            }

            BigInteger p = gost3410Params.P;
            BigInteger a = gost3410Params.A;

            // calculate the public key.
            BigInteger y = a.ModPow(x, p);

            if (param.PublicKeyParamSet != null)
            {
                return(new AsymmetricCipherKeyPair(
                           new Gost3410PublicKeyParameters(y, param.PublicKeyParamSet),
                           new Gost3410PrivateKeyParameters(x, param.PublicKeyParamSet)));
            }

            return(new AsymmetricCipherKeyPair(
                       new Gost3410PublicKeyParameters(y, gost3410Params),
                       new Gost3410PrivateKeyParameters(x, gost3410Params)));
        }
Example #11
0
        public static byte[] GeneratePrivateKey(SecureRandom random = null)
        {
            if (random == null)
            {
                random = new SecureRandom();
            }

            // generates a private key that will always
            // have 32 bits of info and have a a positive
            // public key Y coordinate

            BigInteger n = domainParms.N;
            BigInteger d;
            int        minWeight = n.BitLength / 4;

            for (; ;)
            {
                var bytes = new byte[32];
                random.NextBytes(bytes);
                while (bytes[0] > 127 || bytes[0] == 0)
                {
                    bytes[0] = (byte)random.Next();
                }
                d = new BigInteger(bytes);
                var dbytes = d.ToByteArray();

                var nafWeight = WNafUtilities.GetNafWeight(d);
                if (nafWeight < minWeight)
                {
                    continue;
                }

                var     m = new FixedPointCombMultiplier();
                ECPoint q = m.Multiply(domainParms.G, d).Normalize();

                bool isOdd = q.AffineYCoord.TestBitZero();

                if (!isOdd)
                {
                    return(dbytes);
                }
            }
        }
        /**
         * Given the domain parameters this routine generates an EC key
         * pair in accordance with X9.62 section 5.2.1 pages 26, 27.
         */
        public AsymmetricCipherKeyPair GenerateKeyPair()
        {
            BigInteger n = parameters.N;
            BigInteger d;
            int        minWeight = n.BitLength >> 2;

            for (;;)
            {
                d = new BigInteger(n.BitLength, random);

                if (d.CompareTo(BigInteger.Two) < 0 || d.CompareTo(n) >= 0)
                {
                    continue;
                }

                /*
                 * Require a minimum weight of the NAF representation, since low-weight primes may be
                 * weak against a version of the number-field-sieve for the discrete-logarithm-problem.
                 *
                 * See "The number field sieve for integers of low weight", Oliver Schirokauer.
                 */
                if (WNafUtilities.GetNafWeight(d) < minWeight)
                {
                    continue;
                }

                break;
            }

            ECPoint q = CreateBasePointMultiplier().Multiply(parameters.G, d);

            if (publicKeyParamSet != null)
            {
                return(new AsymmetricCipherKeyPair(
                           new ECPublicKeyParameters(algorithm, q, publicKeyParamSet),
                           new ECPrivateKeyParameters(algorithm, d, publicKeyParamSet)));
            }

            return(new AsymmetricCipherKeyPair(
                       new ECPublicKeyParameters(algorithm, q, parameters),
                       new ECPrivateKeyParameters(algorithm, d, parameters)));
        }
    public AsymmetricCipherKeyPair GenerateKeyPair()
    {
        SecureRandom       random     = param.Random;
        Gost3410Parameters parameters = param.Parameters;
        BigInteger         q          = parameters.Q;
        int        num = 64;
        BigInteger bigInteger;

        do
        {
            bigInteger = new BigInteger(256, random);
        }while (bigInteger.SignValue < 1 || bigInteger.CompareTo(q) >= 0 || WNafUtilities.GetNafWeight(bigInteger) < num);
        BigInteger p = parameters.P;
        BigInteger a = parameters.A;
        BigInteger y = a.ModPow(bigInteger, p);

        if (param.PublicKeyParamSet != null)
        {
            return(new AsymmetricCipherKeyPair(new Gost3410PublicKeyParameters(y, param.PublicKeyParamSet), new Gost3410PrivateKeyParameters(bigInteger, param.PublicKeyParamSet)));
        }
        return(new AsymmetricCipherKeyPair(new Gost3410PublicKeyParameters(y, parameters), new Gost3410PrivateKeyParameters(bigInteger, parameters)));
    }
Example #14
0
        /**
         * Given the domain parameters this routine generates an EC key
         * pair in accordance with X9.62 section 5.2.1 pages 26, 27.
         */
        public AsymmetricCipherKeyPair GenerateKeyPair()
        {
            BigInteger n     = parameters.N;
            BigInteger upper = n.Subtract(BigInteger.Two);
            BigInteger d;
            int        minWeight = n.BitLength >> 2;

            for (;;)
            {
                d = new BigInteger(n.BitLength, random);

                if (d.CompareTo(upper) > 0)
                {
                    continue;
                }

                if (WNafUtilities.GetNafWeight(d) < minWeight)
                {
                    continue;
                }

                break;
            }

            d = d.Add(BigInteger.One);

            ECPoint q = CreateBasePointMultiplier().Multiply(parameters.G, d);

            if (publicKeyParamSet != null)
            {
                return(new AsymmetricCipherKeyPair(
                           new ECPublicKeyParameters(algorithm, q, publicKeyParamSet),
                           new ECPrivateKeyParameters(algorithm, d, publicKeyParamSet)));
            }

            return(new AsymmetricCipherKeyPair(
                       new ECPublicKeyParameters(algorithm, q, parameters),
                       new ECPrivateKeyParameters(algorithm, d, parameters)));
        }
Example #15
0
        internal BigInteger CalculatePrivate(DHParameters dhParams, SecureRandom random)
        {
            BigInteger integer5;
            int        l = dhParams.L;

            if (l != 0)
            {
                BigInteger integer;
                int        num2 = l >> 2;
                do
                {
                    integer = new BigInteger(l, random).SetBit(l - 1);
                }while (WNafUtilities.GetNafWeight(integer) < num2);
                return(integer);
            }
            BigInteger two = BigInteger.Two;
            int        m   = dhParams.M;

            if (m != 0)
            {
                two = BigInteger.One.ShiftLeft(m - 1);
            }
            BigInteger q = dhParams.Q;

            if (q == null)
            {
                q = dhParams.P;
            }
            BigInteger max  = q.Subtract(BigInteger.Two);
            int        num4 = max.BitLength >> 2;

            do
            {
                integer5 = BigIntegers.CreateRandomInRange(two, max, random);
            }while (WNafUtilities.GetNafWeight(integer5) < num4);
            return(integer5);
        }
        internal BigInteger CalculatePrivate(DHParameters dhParams, SecureRandom random)
        {
            int l = dhParams.L;

            if (l != 0)
            {
                int        num = l >> 2;
                BigInteger bigInteger;
                do
                {
                    bigInteger = new BigInteger(l, random).SetBit(l - 1);
                }while (WNafUtilities.GetNafWeight(bigInteger) < num);
                return(bigInteger);
            }
            BigInteger min = BigInteger.Two;
            int        m   = dhParams.M;

            if (m != 0)
            {
                min = BigInteger.One.ShiftLeft(m - 1);
            }
            BigInteger bigInteger2 = dhParams.Q;

            if (bigInteger2 == null)
            {
                bigInteger2 = dhParams.P;
            }
            BigInteger bigInteger3 = bigInteger2.Subtract(BigInteger.Two);
            int        num2        = bigInteger3.BitLength >> 2;
            BigInteger bigInteger4;

            do
            {
                bigInteger4 = BigIntegers.CreateRandomInRange(min, bigInteger3, random);
            }while (WNafUtilities.GetNafWeight(bigInteger4) < num2);
            return(bigInteger4);
        }
Example #17
0
    public BigInteger GenerateRandom()
    {
        BigInteger d;
        int        minWeight = curve.N.BitLength >> 2;

        for (; ;)
        {
            d = new BigInteger(curve.N.BitLength, random);

            if (d.CompareTo(BigInteger.Two) < 0 || d.CompareTo(curve.N) >= 0)
            {
                continue;
            }

            if (WNafUtilities.GetNafWeight(d) < minWeight)
            {
                continue;
            }

            break;
        }

        return(d);
    }
        /*
         * Finds a pair of prime BigInteger's {p, q: p = 2q + 1}
         *
         * (see: Handbook of Applied Cryptography 4.86)
         */
        internal static BigInteger[] GenerateSafePrimes(int size, int certainty, SecureRandom random)
        {
            BigInteger p, q;
            int        qLength   = size - 1;
            int        minWeight = size >> 2;

            if (size <= 32)
            {
                for (;;)
                {
                    q = new BigInteger(qLength, 2, random);

                    p = q.ShiftLeft(1).Add(BigInteger.One);

                    if (!p.IsProbablePrime(certainty, true))
                    {
                        continue;
                    }

                    if (certainty > 2 && !q.IsProbablePrime(certainty, true))
                    {
                        continue;
                    }

                    break;
                }
            }
            else
            {
                // Note: Modified from Java version for speed
                for (;;)
                {
                    q = new BigInteger(qLength, 0, random);

retry:
                    for (int i = 0; i < primeLists.Length; ++i)
                    {
                        int test = q.Remainder(BigPrimeProducts[i]).IntValue;

                        if (i == 0)
                        {
                            int rem3 = test % 3;
                            if (rem3 != 2)
                            {
                                int diff = 2 * rem3 + 2;
                                q    = q.Add(BigInteger.ValueOf(diff));
                                test = (test + diff) % primeProducts[i];
                            }
                        }

                        int[] primeList = primeLists[i];
                        for (int j = 0; j < primeList.Length; ++j)
                        {
                            int prime = primeList[j];
                            int qRem  = test % prime;
                            if (qRem == 0 || qRem == (prime >> 1))
                            {
                                q = q.Add(Six);
                                goto retry;
                            }
                        }
                    }

                    if (q.BitLength != qLength)
                    {
                        continue;
                    }

                    if (!q.RabinMillerTest(2, random, true))
                    {
                        continue;
                    }

                    p = q.ShiftLeft(1).Add(BigInteger.One);

                    if (!p.RabinMillerTest(certainty, random, true))
                    {
                        continue;
                    }

                    if (certainty > 2 && !q.RabinMillerTest(certainty - 2, random, true))
                    {
                        continue;
                    }

                    /*
                     * Require a minimum weight of the NAF representation, since low-weight primes may be
                     * weak against a version of the number-field-sieve for the discrete-logarithm-problem.
                     *
                     * See "The number field sieve for integers of low weight", Oliver Schirokauer.
                     */
                    if (WNafUtilities.GetNafWeight(p) < minWeight)
                    {
                        continue;
                    }

                    break;
                }
            }

            return(new BigInteger[] { p, q });
        }
        internal static BigInteger[] GenerateSafePrimes(int size, int certainty, SecureRandom random)
        {
            int        num  = size - 1;
            int        num2 = size >> 2;
            BigInteger bigInteger;
            BigInteger bigInteger2;

            if (size <= 32)
            {
                while (true)
                {
                    bigInteger  = new BigInteger(num, 2, random);
                    bigInteger2 = bigInteger.ShiftLeft(1).Add(BigInteger.One);
                    if (bigInteger2.IsProbablePrime(certainty))
                    {
                        if (certainty <= 2 || bigInteger.IsProbablePrime(certainty - 2))
                        {
                            break;
                        }
                    }
                }
            }
            else
            {
                while (true)
                {
                    bigInteger = new BigInteger(num, 0, random);
                    while (true)
                    {
IL_51:
                        for (int i = 0; i < DHParametersHelper.primeLists.Length; i++)
                        {
                            int num3 = bigInteger.Remainder(DHParametersHelper.BigPrimeProducts[i]).IntValue;
                            if (i == 0)
                            {
                                int num4 = num3 % 3;
                                if (num4 != 2)
                                {
                                    int num5 = 2 * num4 + 2;
                                    bigInteger = bigInteger.Add(BigInteger.ValueOf((long)num5));
                                    num3       = (num3 + num5) % DHParametersHelper.primeProducts[i];
                                }
                            }
                            int[] array = DHParametersHelper.primeLists[i];
                            for (int j = 0; j < array.Length; j++)
                            {
                                int num6 = array[j];
                                int num7 = num3 % num6;
                                if (num7 == 0 || num7 == num6 >> 1)
                                {
                                    bigInteger = bigInteger.Add(DHParametersHelper.Six);
                                    goto IL_51;
                                }
                            }
                        }
                        break;
                    }
                    if (bigInteger.BitLength == num && bigInteger.RabinMillerTest(2, random))
                    {
                        bigInteger2 = bigInteger.ShiftLeft(1).Add(BigInteger.One);
                        if (bigInteger2.RabinMillerTest(certainty, random) && (certainty <= 2 || bigInteger.RabinMillerTest(certainty - 2, random)) && WNafUtilities.GetNafWeight(bigInteger2) >= num2)
                        {
                            break;
                        }
                    }
                }
            }
            return(new BigInteger[]
            {
                bigInteger2,
                bigInteger
            });
        }
Example #20
0
        public AsymmetricCipherKeyPair GenerateKeyPair()
        {
            BigInteger integer2;
            BigInteger n   = this.parameters.N;
            int        num = n.BitLength >> 2;

            do
            {
                integer2 = new BigInteger(n.BitLength, this.random);
            }while (((integer2.CompareTo(BigInteger.Two) < 0) || (integer2.CompareTo(n) >= 0)) || (WNafUtilities.GetNafWeight(integer2) < num));
            ECPoint q = this.CreateBasePointMultiplier().Multiply(this.parameters.G, integer2);

            if (this.publicKeyParamSet != null)
            {
                return(new AsymmetricCipherKeyPair(new ECPublicKeyParameters(this.algorithm, q, this.publicKeyParamSet), new ECPrivateKeyParameters(this.algorithm, integer2, this.publicKeyParamSet)));
            }
            return(new AsymmetricCipherKeyPair(new ECPublicKeyParameters(this.algorithm, q, this.parameters), new ECPrivateKeyParameters(this.algorithm, integer2, this.parameters)));
        }
Example #21
0
    public AsymmetricCipherKeyPair GenerateKeyPair()
    {
        BigInteger n   = parameters.N;
        int        num = n.BitLength >> 2;
        BigInteger bigInteger;

        do
        {
            bigInteger = new BigInteger(n.BitLength, random);
        }while (bigInteger.CompareTo(BigInteger.Two) < 0 || bigInteger.CompareTo(n) >= 0 || WNafUtilities.GetNafWeight(bigInteger) < num);
        ECPoint q = CreateBasePointMultiplier().Multiply(parameters.G, bigInteger);

        if (publicKeyParamSet != null)
        {
            return(new AsymmetricCipherKeyPair(new ECPublicKeyParameters(algorithm, q, publicKeyParamSet), new ECPrivateKeyParameters(algorithm, bigInteger, publicKeyParamSet)));
        }
        return(new AsymmetricCipherKeyPair(new ECPublicKeyParameters(algorithm, q, parameters), new ECPrivateKeyParameters(algorithm, bigInteger, parameters)));
    }
        public AsymmetricCipherKeyPair GenerateKeyPair()
        {
            AsymmetricCipherKeyPair result = null;
            bool done = false;

            //
            // 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 / 2) - 100;
            int minWeight   = strength >> 2;

            // for approved mode operation this will never happen, but in case
            // someone is doing something "different" we make sure mindiffbits  is
            // always sensible.
            if (mindiffbits < strength / 3)
            {
                mindiffbits = strength / 3;
            }

            // d lower bound is 2^(strength / 2)
            BigInteger dLowerBound = BigInteger.Two.Pow(strength / 2);
            // squared bound (sqrt(2)*2^(nlen/2-1))^2
            BigInteger squaredBound = BigInteger.One.ShiftLeft(strength - 1);
            // 2^(nlen/2 - 100)
            BigInteger minDiff = BigInteger.One.ShiftLeft(mindiffbits);

            while (!done)
            {
                BigInteger p, q, n, d, e, pSub1, qSub1, gcd, lcm;

                e = param.PublicExponent;

                p = chooseRandomPrime(pbitlength, e, squaredBound);

                //
                // generate a modulus of the required length
                //
                for (;;)
                {
                    q = chooseRandomPrime(qbitlength, e, squaredBound);

                    // p and q should not be too close together (or equal!)
                    BigInteger diff = q.Subtract(p).Abs();
                    if (diff.BitLength < mindiffbits || diff.CompareTo(minDiff) <= 0)
                    {
                        continue;
                    }

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

                    if (n.BitLength != strength)
                    {
                        //
                        // if we get here our primes aren't big enough, make the largest
                        // of the two p and try again
                        //
                        p = p.Max(q);
                        continue;
                    }

                    /*
                     * Require a minimum weight of the NAF representation, since low-weight composites may
                     * be weak against a version of the number-field-sieve for factoring.
                     *
                     * See "The number field sieve for integers of low weight", Oliver Schirokauer.
                     */
                    if (WNafUtilities.GetNafWeight(n) < minWeight)
                    {
                        p = chooseRandomPrime(pbitlength, e, squaredBound);
                        continue;
                    }

                    break;
                }

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

                pSub1 = p.Subtract(BigInteger.One);
                qSub1 = q.Subtract(BigInteger.One);
                gcd   = pSub1.Gcd(qSub1);
                lcm   = pSub1.Divide(gcd).Multiply(qSub1);

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

                if (d.CompareTo(dLowerBound) <= 0)
                {
                    continue;
                }
                else
                {
                    done = true;
                }

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

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

                result = new AsymmetricCipherKeyPair(
                    new RsaKeyParameters(false, n, e),
                    new RsaPrivateCrtKeyParameters(n, e, d, p, q, dP, dQ, qInv));
            }

            return(result);
        }
Example #23
0
        internal static BigInteger[] GenerateSafePrimes(int size, int certainty, SecureRandom random)
        {
            int        num  = size - 1;
            int        num2 = size >> 2;
            BigInteger bigInteger;
            BigInteger bigInteger2;

            if (size <= 32)
            {
                do
                {
                    bigInteger  = new BigInteger(num, 2, (Random)(object)random);
                    bigInteger2 = bigInteger.ShiftLeft(1).Add(BigInteger.One);
                }while (!bigInteger2.IsProbablePrime(certainty, randomlySelected: true) || (certainty > 2 && !bigInteger.IsProbablePrime(certainty, randomlySelected: true)));
            }
            else
            {
                while (true)
                {
                    bigInteger = new BigInteger(num, 0, (Random)(object)random);
                    while (true)
                    {
                        for (int i = 0; i < primeLists.Length; i++)
                        {
                            int num3 = bigInteger.Remainder(BigPrimeProducts[i]).IntValue;
                            if (i == 0)
                            {
                                int num4 = num3 % 3;
                                if (num4 != 2)
                                {
                                    int num5 = 2 * num4 + 2;
                                    bigInteger = bigInteger.Add(BigInteger.ValueOf(num5));
                                    num3       = (num3 + num5) % primeProducts[i];
                                }
                            }
                            int[] array = primeLists[i];
                            foreach (int num6 in array)
                            {
                                int num7 = num3 % num6;
                                if (num7 == 0 || num7 == num6 >> 1)
                                {
                                    goto IL_00cd;
                                }
                            }
                        }
                        break;
IL_00cd:
                        bigInteger = bigInteger.Add(Six);
                    }
                    if (bigInteger.BitLength == num && bigInteger.RabinMillerTest(2, (Random)(object)random, randomlySelected: true))
                    {
                        bigInteger2 = bigInteger.ShiftLeft(1).Add(BigInteger.One);
                        if (bigInteger2.RabinMillerTest(certainty, (Random)(object)random, randomlySelected: true) && (certainty <= 2 || bigInteger.RabinMillerTest(certainty - 2, (Random)(object)random, randomlySelected: true)) && WNafUtilities.GetNafWeight(bigInteger2) >= num2)
                        {
                            break;
                        }
                    }
                }
            }
            return(new BigInteger[2] {
                bigInteger2, bigInteger
            });
        }
Example #24
0
            public override AsymmetricCipherKeyPair GenerateKeyPair()
            {
                for (; ;)
                {
                    //
                    // p and q values should have a length of half the strength in bits
                    //
                    int strength    = this.parameters.Strength;
                    int pBitLength  = (strength + 1) / 2;
                    int qBitLength  = strength - pBitLength;
                    int mindiffbits = strength / 3;
                    int minWeight   = strength >> 2;

                    if ((pBitLength % 8 != 0) || (qBitLength % 8 != 0))
                    {
                        throw new Exception($"The bitlength of both p and q must be a multilple of 8.");
                    }

                    byte[]     pBytes      = this.generatorKey.Take(pBitLength / 8).ToArray();
                    BigInteger pStartValue = new BigInteger(+1, pBytes);

                    byte[]     qBytes      = this.generatorKey.Skip(Math.Max(0, this.generatorKey.Count() - (qBitLength / 8))).ToArray();
                    BigInteger qStartValue = new BigInteger(+1, qBytes);

                    BigInteger e = this.parameters.PublicExponent;

                    // p should always be higher than q
                    if (pStartValue.CompareTo(qStartValue) < 0)
                    {
                        BigInteger temp = pStartValue;
                        pStartValue = qStartValue;
                        qStartValue = temp;
                    }

                    BigInteger p = ChooseNthPrime(pStartValue, e, +1, pBitLength);
                    BigInteger q = ChooseNthPrime(qStartValue, e, -1, qBitLength);
                    BigInteger n;

                    //
                    // generate a modulus of the required length
                    //
                    bool changeP = false;
                    for (; ;)
                    {
                        if (changeP)
                        {
                            p = ChooseNthPrime(p, e, +1, pBitLength);
                        }
                        else
                        {
                            q = ChooseNthPrime(q, e, -1, qBitLength);
                        }
                        changeP = !changeP;

                        // p and q should not be too close together (or equal!)
                        BigInteger diff = p.Subtract(q).Abs();
                        if (diff.BitLength < mindiffbits)
                        {
                            Console.WriteLine($" -NOTE- The difference between the two primes are only {diff.BitLength} and the requirement is {mindiffbits}. Retrying...");

                            continue;
                        }

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

                        if (n.BitLength != strength)
                        {
                            //
                            // if we get here our primes aren't big enough, make the largest
                            // of the two p and try again
                            //
                            Console.WriteLine($" -NOTE- The modulus bit strength is {n.BitLength} and the requirement is {strength}. Retrying...");

                            if (!p.TestBit(p.BitLength - 2))
                            {
                                p       = p.SetBit(p.BitLength - 2);
                                changeP = true;
                            }
                            else if (!q.TestBit(q.BitLength - 2))
                            {
                                q       = q.SetBit(q.BitLength - 2);
                                changeP = false;
                            }

                            continue;
                        }

                        /*
                         * Require a minimum weight of the NAF representation, since low-weight composites may
                         * be weak against a version of the number-field-sieve for factoring.
                         *
                         * See "The number field sieve for integers of low weight", Oliver Schirokauer.
                         */
                        if (WNafUtilities.GetNafWeight(n) < minWeight)
                        {
                            Console.WriteLine($" -NOTE- The NAF weight is {WNafUtilities.GetNafWeight(n)} and the requirement is {minWeight}. Retrying...");

                            continue;
                        }

                        break;
                    }

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

                    BigInteger pSub1 = p.Subtract(One);
                    BigInteger qSub1 = q.Subtract(One);
                    //BigInteger phi = pSub1.Multiply(qSub1);
                    BigInteger gcd = pSub1.Gcd(qSub1);
                    BigInteger lcm = pSub1.Divide(gcd).Multiply(qSub1);

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

                    if (d.BitLength <= qBitLength)
                    {
                        continue;
                    }

                    //
                    // calculate the CRT factors
                    //
                    BigInteger dP   = d.Remainder(pSub1);
                    BigInteger dQ   = d.Remainder(qSub1);
                    BigInteger qInv = q.ModInverse(p);

                    return(new AsymmetricCipherKeyPair(
                               new RsaKeyParameters(false, n, e),
                               new RsaPrivateCrtKeyParameters(n, e, d, p, q, dP, dQ, qInv)));
                }
            }
Example #25
0
        internal static BigInteger[] GenerateSafePrimes(int size, int certainty, SecureRandom random)
        {
            int        num  = size - 1;
            int        num2 = size >> 2;
            BigInteger bigInteger;
            BigInteger bigInteger2;

            if (size > 32)
            {
                while (true)
                {
                    bigInteger = new BigInteger(num, 0, random);
                    while (true)
                    {
                        for (int i = 0; i < primeLists.Length; i++)
                        {
                            int num3 = bigInteger.Remainder(BigPrimeProducts[i]).IntValue;
                            if (i == 0)
                            {
                                int num4 = num3 % 3;
                                if (num4 != 2)
                                {
                                    int num5 = 2 * num4 + 2;
                                    bigInteger = bigInteger.Add(BigInteger.ValueOf(num5));
                                    num3       = (num3 + num5) % primeProducts[i];
                                }
                            }
                            int[] array = primeLists[i];
                            int   num6  = 0;
                            while (num6 < array.Length)
                            {
                                int num7 = array[num6];
                                int num8 = num3 % num7;
                                if (num8 != 0 && num8 != num7 >> 1)
                                {
                                    num6++;
                                    continue;
                                }
                                goto IL_0103;
                            }
                        }
                        break;
IL_0103:
                        bigInteger = bigInteger.Add(Six);
                    }
                    if (bigInteger.BitLength == num && bigInteger.RabinMillerTest(2, random))
                    {
                        bigInteger2 = bigInteger.ShiftLeft(1).Add(BigInteger.One);
                        if (bigInteger2.RabinMillerTest(certainty, random) && (certainty <= 2 || bigInteger.RabinMillerTest(certainty - 2, random)) && WNafUtilities.GetNafWeight(bigInteger2) >= num2)
                        {
                            break;
                        }
                    }
                }
            }
            else
            {
                do
                {
                    bigInteger  = new BigInteger(num, 2, random);
                    bigInteger2 = bigInteger.ShiftLeft(1).Add(BigInteger.One);
                }while (!bigInteger2.IsProbablePrime(certainty) || (certainty > 2 && !bigInteger.IsProbablePrime(certainty - 2)));
            }
            return(new BigInteger[2]
            {
                bigInteger2,
                bigInteger
            });
        }
Example #26
0
        public virtual AsymmetricCipherKeyPair GenerateKeyPair()
        {
            for (;;)
            {
                //
                // p and q values should have a length of half the strength in bits
                //
                int strength    = parameters.Strength;
                int pBitlength  = (strength + 1) / 2;
                int qBitlength  = strength - pBitlength;
                int mindiffbits = strength / 3;
                int minWeight   = strength >> 2;

                BigInteger e = parameters.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")

                BigInteger p = ChooseRandomPrime(pBitlength, e);
                BigInteger q, n;

                //
                // generate a modulus of the required length
                //
                for (;;)
                {
                    q = ChooseRandomPrime(qBitlength, e);

                    // p and q should not be too close together (or equal!)
                    BigInteger diff = q.Subtract(p).Abs();
                    if (diff.BitLength < mindiffbits)
                    {
                        continue;
                    }

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

                    if (n.BitLength != strength)
                    {
                        //
                        // if we get here our primes aren't big enough, make the largest
                        // of the two p and try again
                        //
                        p = p.Max(q);
                        continue;
                    }

                    /*
                     * Require a minimum weight of the NAF representation, since low-weight composites may
                     * be weak against a version of the number-field-sieve for factoring.
                     *
                     * See "The number field sieve for integers of low weight", Oliver Schirokauer.
                     */
                    if (WNafUtilities.GetNafWeight(n) < minWeight)
                    {
                        p = ChooseRandomPrime(pBitlength, e);
                        continue;
                    }

                    break;
                }

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

                BigInteger pSub1 = p.Subtract(One);
                BigInteger qSub1 = q.Subtract(One);
                //BigInteger phi = pSub1.Multiply(qSub1);
                BigInteger gcd = pSub1.Gcd(qSub1);
                BigInteger lcm = pSub1.Divide(gcd).Multiply(qSub1);

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

                if (d.BitLength <= qBitlength)
                {
                    continue;
                }

                //
                // calculate the CRT factors
                //
                BigInteger dP   = d.Remainder(pSub1);
                BigInteger dQ   = d.Remainder(qSub1);
                BigInteger qInv = q.ModInverse(p);

                return(new AsymmetricCipherKeyPair(
                           new RsaKeyParameters(false, n, e),
                           new RsaPrivateCrtKeyParameters(n, e, d, p, q, dP, dQ, qInv)));
            }
        }
        internal static BigInteger[] GenerateSafePrimes(int size, int certainty, SecureRandom random)
        {
            BigInteger integer;
            BigInteger integer2;
            int        num3;
            int        bitLength = size - 1;
            int        num2      = size >> 2;

            if (size <= 0x20)
            {
                while (true)
                {
                    integer2 = new BigInteger(bitLength, 2, random);
                    integer  = integer2.ShiftLeft(1).Add(BigInteger.One);
                    if (integer.IsProbablePrime(certainty, true) && ((certainty <= 2) || integer2.IsProbablePrime(certainty, true)))
                    {
                        goto Label_01B9;
                    }
                }
            }
Label_006F:
            integer2 = new BigInteger(bitLength, 0, random);
Label_0078:
            num3 = 0;
            while (num3 < primeLists.Length)
            {
                int intValue = integer2.Remainder(BigPrimeProducts[num3]).IntValue;
                if (num3 == 0)
                {
                    int num5 = intValue % 3;
                    if (num5 != 2)
                    {
                        int num6 = (2 * num5) + 2;
                        integer2 = integer2.Add(BigInteger.ValueOf((long)num6));
                        intValue = (intValue + num6) % primeProducts[num3];
                    }
                }
                foreach (int num8 in primeLists[num3])
                {
                    int num9 = intValue % num8;
                    if ((num9 == 0) || (num9 == (num8 >> 1)))
                    {
                        integer2 = integer2.Add(Six);
                        goto Label_0078;
                    }
                }
                num3++;
            }
            if ((integer2.BitLength != bitLength) || !integer2.RabinMillerTest(2, random, true))
            {
                goto Label_006F;
            }
            integer = integer2.ShiftLeft(1).Add(BigInteger.One);
            if ((!integer.RabinMillerTest(certainty, random, true) || ((certainty > 2) && !integer2.RabinMillerTest(certainty - 2, random, true))) || (WNafUtilities.GetNafWeight(integer) < num2))
            {
                goto Label_006F;
            }
Label_01B9:
            return(new BigInteger[] { integer, integer2 });
        }