Esempio n. 1
0
        /**
         * Generates client's credentials given the client's salt, identity and password
         * @param salt The salt used in the client's verifier.
         * @param identity The user's identity (eg. username)
         * @param password The user's password
         * @return Client's public value to send to server
         */
        public virtual IBigInteger GenerateClientCredentials(byte[] salt, byte[] identity, byte[] password)
        {
            this.x     = Srp6Utilities.CalculateX(digest, N, salt, identity, password);
            this.privA = SelectPrivateValue();
            this.pubA  = g.ModPow(privA, N);

            return(pubA);
        }
Esempio n. 2
0
        public IAsymmetricCipherKeyPair GenerateKeyPair()
        {
            ISecureRandom      random         = param.Random;
            Gost3410Parameters gost3410Params = param.Parameters;

            IBigInteger q = gost3410Params.Q;
            IBigInteger x;

            do
            {
                x = new BigInteger(256, random);
            }while (x.SignValue < 1 || x.CompareTo(q) >= 0);

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

            // calculate the public key.
            IBigInteger 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)));
        }
Esempio n. 3
0
        /**
         * Generates the server's credentials that are to be sent to the client.
         * @return The server's public value to the client
         */
        public virtual IBigInteger GenerateServerCredentials()
        {
            IBigInteger k = Srp6Utilities.CalculateK(digest, N, g);

            this.privB = SelectPrivateValue();
            this.pubB  = k.Multiply(v).Mod(N).Add(g.ModPow(privB, N)).Mod(N);

            return(pubB);
        }
        /*
         * Blind message with the blind factor.
         */
        private IBigInteger BlindMessage(
            IBigInteger msg)
        {
            IBigInteger blindMsg = blindingFactor;

            blindMsg = msg.Multiply(blindMsg.ModPow(key.Exponent, key.Modulus));
            blindMsg = blindMsg.Mod(key.Modulus);

            return(blindMsg);
        }
        public void TestModPow()
        {
            try
            {
                two.ModPow(one, zero);
                Assert.Fail("expected ArithmeticException");
            }
            catch (ArithmeticException) {}

            Assert.AreEqual(zero, zero.ModPow(zero, one));
            Assert.AreEqual(one, zero.ModPow(zero, two));
            Assert.AreEqual(zero, two.ModPow(one, one));
            Assert.AreEqual(one, two.ModPow(zero, two));

            for (int i = 0; i < 10; ++i)
            {
                IBigInteger m = BigInteger.ProbablePrime(10 + i * 3, _random);
                IBigInteger x = new BigInteger(m.BitLength - 1, _random);

                Assert.AreEqual(x, x.ModPow(m, m));
                if (x.SignValue != 0)
                {
                    Assert.AreEqual(zero, zero.ModPow(x, m));
                    Assert.AreEqual(one, x.ModPow(m.Subtract(one), m));
                }

                IBigInteger y  = new BigInteger(m.BitLength - 1, _random);
                IBigInteger n  = new BigInteger(m.BitLength - 1, _random);
                IBigInteger n3 = n.ModPow(three, m);

                IBigInteger resX = n.ModPow(x, m);
                IBigInteger resY = n.ModPow(y, m);
                IBigInteger res  = resX.Multiply(resY).Mod(m);
                IBigInteger res3 = res.ModPow(three, m);

                Assert.AreEqual(res3, n3.ModPow(x.Add(y), m));

                IBigInteger a = x.Add(one);                 // Make sure it's not zero
                IBigInteger b = y.Add(one);                 // Make sure it's not zero

                Assert.AreEqual(a.ModPow(b, m).ModInverse(m), a.ModPow(b.Negate(), m));
            }
        }
        /**
         * given a message from a given party and the corresponding public key
         * calculate the next message in the agreement sequence. In this case
         * this will represent the shared secret.
         */
        public IBigInteger CalculateAgreement(DHPublicKeyParameters pub, IBigInteger message)
        {
            if (pub == null)
                throw new ArgumentNullException("pub");
            if (message == null)
                throw new ArgumentNullException("message");

            if (!pub.Parameters.Equals(_dhParams))
            {
                throw new ArgumentException("Diffie-Hellman public key has wrong parameters.");
            }

            var p = _dhParams.P;
            return message.ModPow(_key.X, p).Multiply(pub.Y.ModPow(_privateValue, p)).Mod(p);
        }
        private static IBigInteger CalculateGenerator_FIPS186_2(IBigInteger p, IBigInteger q, SecureRandom r)
        {
            IBigInteger e     = p.Subtract(BigInteger.One).Divide(q);
            IBigInteger pSub2 = p.Subtract(BigInteger.Two);

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

                if (g.BitLength > 1)
                {
                    return(g);
                }
            }
        }
Esempio n. 8
0
        /**
         * Process a single block using the basic RSA algorithm.
         *
         * @param inBuf the input array.
         * @param inOff the offset into the input buffer where the data starts.
         * @param inLen the length of the data to be processed.
         * @return the result of the RSA process.
         * @exception DataLengthException the input block is too large.
         */
        public byte[] ProcessBlock(
            byte[]  inBuf,
            int inOff,
            int inLen)
        {
            if (key == null)
            {
                throw new InvalidOperationException("RSA engine not initialised");
            }

            IBigInteger input = core.ConvertInput(inBuf, inOff, inLen);

            IBigInteger result;

            if (key is RsaPrivateCrtKeyParameters)
            {
                RsaPrivateCrtKeyParameters k = (RsaPrivateCrtKeyParameters)key;
                IBigInteger e = k.PublicExponent;
                if (e != null)                   // can't do blinding without a public exponent
                {
                    IBigInteger m = k.Modulus;
                    IBigInteger r = BigIntegers.CreateRandomInRange(
                        BigInteger.One, m.Subtract(BigInteger.One), random);

                    IBigInteger blindedInput  = r.ModPow(e, m).Multiply(input).Mod(m);
                    IBigInteger blindedResult = core.ProcessBlock(blindedInput);

                    IBigInteger rInv = r.ModInverse(m);
                    result = blindedResult.Multiply(rInv).Mod(m);
                }
                else
                {
                    result = core.ProcessBlock(input);
                }
            }
            else
            {
                result = core.ProcessBlock(input);
            }

            return(core.ConvertOutput(result));
        }
        /**
         * given a message from a given party and the corresponding public key
         * calculate the next message in the agreement sequence. In this case
         * this will represent the shared secret.
         */
        public IBigInteger CalculateAgreement(DHPublicKeyParameters pub, IBigInteger message)
        {
            if (pub == null)
            {
                throw new ArgumentNullException("pub");
            }
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            if (!pub.Parameters.Equals(_dhParams))
            {
                throw new ArgumentException("Diffie-Hellman public key has wrong parameters.");
            }

            var p = _dhParams.P;

            return(message.ModPow(_key.X, p).Multiply(pub.Y.ModPow(_privateValue, p)).Mod(p));
        }
        public IBigInteger ProcessBlock(
            IBigInteger input)
        {
            if (key is RsaPrivateCrtKeyParameters)
            {
                //
                // we have the extra factors, use the Chinese Remainder Theorem - the author
                // wishes to express his thanks to Dirk Bonekaemper at rtsffm.com for
                // advice regarding the expression of this.
                //
                RsaPrivateCrtKeyParameters crtKey = (RsaPrivateCrtKeyParameters)key;

                IBigInteger p    = crtKey.P;;
                IBigInteger q    = crtKey.Q;
                IBigInteger dP   = crtKey.DP;
                IBigInteger dQ   = crtKey.DQ;
                IBigInteger qInv = crtKey.QInv;

                IBigInteger mP, mQ, h, m;

                // mP = ((input Mod p) ^ dP)) Mod p
                mP = (input.Remainder(p)).ModPow(dP, p);

                // mQ = ((input Mod q) ^ dQ)) Mod q
                mQ = (input.Remainder(q)).ModPow(dQ, q);

                // h = qInv * (mP - mQ) Mod p
                h = mP.Subtract(mQ);
                h = h.Multiply(qInv);
                h = h.Mod(p);                               // Mod (in Java) returns the positive residual

                // m = h * q + mQ
                m = h.Multiply(q);
                m = m.Add(mQ);

                return(m);
            }

            return(input.ModPow(key.Exponent, key.Modulus));
        }
 private static IBigInteger CalculatePublicKey(IBigInteger p, IBigInteger g, IBigInteger x)
 {
     return(g.ModPow(x, p));
 }
        public IBigInteger ProcessBlock(
			IBigInteger input)
        {
            if (key is RsaPrivateCrtKeyParameters)
            {
                //
                // we have the extra factors, use the Chinese Remainder Theorem - the author
                // wishes to express his thanks to Dirk Bonekaemper at rtsffm.com for
                // advice regarding the expression of this.
                //
                RsaPrivateCrtKeyParameters crtKey = (RsaPrivateCrtKeyParameters)key;

                IBigInteger p = crtKey.P;;
                IBigInteger q = crtKey.Q;
                IBigInteger dP = crtKey.DP;
                IBigInteger dQ = crtKey.DQ;
                IBigInteger qInv = crtKey.QInv;

                IBigInteger mP, mQ, h, m;

                // mP = ((input Mod p) ^ dP)) Mod p
                mP = (input.Remainder(p)).ModPow(dP, p);

                // mQ = ((input Mod q) ^ dQ)) Mod q
                mQ = (input.Remainder(q)).ModPow(dQ, q);

                // h = qInv * (mP - mQ) Mod p
                h = mP.Subtract(mQ);
                h = h.Multiply(qInv);
                h = h.Mod(p);               // Mod (in Java) returns the positive residual

                // m = h * q + mQ
                m = h.Multiply(q);
                m = m.Add(mQ);

                return m;
            }

            return input.ModPow(key.Exponent, key.Modulus);
        }
 private static IBigInteger CalculatePublicKey(IBigInteger p, IBigInteger g, IBigInteger x)
 {
     return g.ModPow(x, p);
 }
Esempio n. 14
0
        /**
         * Creates a new SRP verifier
         * @param salt The salt to use, generally should be large and random
         * @param identity The user's identifying information (eg. username)
         * @param password The user's password
         * @return A new verifier for use in future SRP authentication
         */
        public virtual IBigInteger GenerateVerifier(byte[] salt, byte[] identity, byte[] password)
        {
            IBigInteger x = Srp6Utilities.CalculateX(digest, N, salt, identity, password);

            return(g.ModPow(x, N));
        }
Esempio n. 15
0
 private IBigInteger CalculateS()
 {
     return(v.ModPow(u, N).Multiply(A).Mod(N).ModPow(privB, N));
 }
        /*
         * (non-Javadoc)
         *
         * @see org.bouncycastle.crypto.AsymmetricCipherKeyPairGenerator#generateKeyPair()
         */
        public IAsymmetricCipherKeyPair GenerateKeyPair()
        {
            int           strength  = param.Strength;
            ISecureRandom rand      = param.Random;
            int           certainty = param.Certainty;
            bool          debug     = param.IsDebug;

#if !NETFX_CORE
            if (debug)
            {
                Console.WriteLine("Fetching first " + param.CountSmallPrimes + " primes.");
            }
#endif

            IList smallPrimes = findFirstPrimes(param.CountSmallPrimes);

            smallPrimes = PermuteList(smallPrimes, rand);

            IBigInteger u = BigInteger.One;
            IBigInteger v = BigInteger.One;

            for (int i = 0; i < smallPrimes.Count / 2; i++)
            {
                u = u.Multiply((BigInteger)smallPrimes[i]);
            }
            for (int i = smallPrimes.Count / 2; i < smallPrimes.Count; i++)
            {
                v = v.Multiply((BigInteger)smallPrimes[i]);
            }

            IBigInteger sigma = u.Multiply(v);

            // n = (2 a u _p + 1 ) ( 2 b v _q + 1)
            // -> |n| = strength
            // |2| = 1 in bits
            // -> |a| * |b| = |n| - |u| - |v| - |_p| - |_q| - |2| -|2|
            // remainingStrength = strength - sigma.bitLength() - _p.bitLength() -
            // _q.bitLength() - 1 -1
            int         remainingStrength = strength - sigma.BitLength - 48;
            IBigInteger a = GeneratePrime(remainingStrength / 2 + 1, certainty, rand);
            IBigInteger b = GeneratePrime(remainingStrength / 2 + 1, certainty, rand);

            IBigInteger _p;
            IBigInteger _q;
            IBigInteger p;
            IBigInteger q;

            long tries = 0;
#if !NETFX_CORE
            if (debug)
            {
                Console.WriteLine("generating p and q");
            }
#endif

            IBigInteger _2au = a.Multiply(u).ShiftLeft(1);
            IBigInteger _2bv = b.Multiply(v).ShiftLeft(1);

            for (; ;)
            {
                tries++;

                _p = GeneratePrime(24, certainty, rand);

                p = _p.Multiply(_2au).Add(BigInteger.One);

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

                for (; ;)
                {
                    _q = GeneratePrime(24, certainty, rand);

                    if (_p.Equals(_q))
                    {
                        continue;
                    }

                    q = _q.Multiply(_2bv).Add(BigInteger.One);

                    if (q.IsProbablePrime(certainty))
                    {
                        break;
                    }
                }

                if (!sigma.Gcd(_p.Multiply(_q)).Equals(BigInteger.One))
                {
#if !NETFX_CORE
                    Console.WriteLine("sigma.gcd(_p.mult(_q)) != 1!\n _p: " + _p + "\n _q: " + _q);
#endif
                    continue;
                }

                if (p.Multiply(q).BitLength < strength)
                {
#if !NETFX_CORE
                    if (debug)
                    {
                        Console.WriteLine("key size too small. Should be " + strength + " but is actually "
                                          + p.Multiply(q).BitLength);
                    }
#endif
                    continue;
                }
                break;
            }

#if !NETFX_CORE
            if (debug)
            {
                Console.WriteLine("needed " + tries + " tries to generate p and q.");
            }
#endif

            IBigInteger n     = p.Multiply(q);
            IBigInteger phi_n = p.Subtract(BigInteger.One).Multiply(q.Subtract(BigInteger.One));
            IBigInteger g;
            tries = 0;
#if !NETFX_CORE
            if (debug)
            {
                Console.WriteLine("generating g");
            }
#endif
            for (; ;)
            {
                // TODO After the first loop, just regenerate one randomly-selected gPart each time?
                IList gParts = Platform.CreateArrayList();
                for (int ind = 0; ind != smallPrimes.Count; ind++)
                {
                    IBigInteger i = (BigInteger)smallPrimes[ind];
                    IBigInteger e = phi_n.Divide(i);

                    for (; ;)
                    {
                        tries++;

                        g = GeneratePrime(strength, certainty, rand);

                        if (!g.ModPow(e, n).Equals(BigInteger.One))
                        {
                            gParts.Add(g);
                            break;
                        }
                    }
                }
                g = BigInteger.One;
                for (int i = 0; i < smallPrimes.Count; i++)
                {
                    IBigInteger gPart      = (BigInteger)gParts[i];
                    IBigInteger smallPrime = (BigInteger)smallPrimes[i];
                    g = g.Multiply(gPart.ModPow(sigma.Divide(smallPrime), n)).Mod(n);
                }

                // make sure that g is not divisible by p_i or q_i
                bool divisible = false;
                for (int i = 0; i < smallPrimes.Count; i++)
                {
                    if (g.ModPow(phi_n.Divide((BigInteger)smallPrimes[i]), n).Equals(BigInteger.One))
                    {
#if !NETFX_CORE
                        if (debug)
                        {
                            Console.WriteLine("g has order phi(n)/" + smallPrimes[i] + "\n g: " + g);
                        }
#endif
                        divisible = true;
                        break;
                    }
                }

                if (divisible)
                {
                    continue;
                }

                // make sure that g has order > phi_n/4

                //if (g.ModPow(phi_n.Divide(BigInteger.ValueOf(4)), n).Equals(BigInteger.One))
                if (g.ModPow(phi_n.ShiftRight(2), n).Equals(BigInteger.One))
                {
#if !NETFX_CORE
                    if (debug)
                    {
                        Console.WriteLine("g has order phi(n)/4\n g:" + g);
                    }
#endif
                    continue;
                }

                if (g.ModPow(phi_n.Divide(_p), n).Equals(BigInteger.One))
                {
#if !NETFX_CORE
                    if (debug)
                    {
                        Console.WriteLine("g has order phi(n)/p'\n g: " + g);
                    }
#endif
                    continue;
                }
                if (g.ModPow(phi_n.Divide(_q), n).Equals(BigInteger.One))
                {
#if !NETFX_CORE
                    if (debug)
                    {
                        Console.WriteLine("g has order phi(n)/q'\n g: " + g);
                    }
#endif
                    continue;
                }
                if (g.ModPow(phi_n.Divide(a), n).Equals(BigInteger.One))
                {
#if !NETFX_CORE
                    if (debug)
                    {
                        Console.WriteLine("g has order phi(n)/a\n g: " + g);
                    }
#endif
                    continue;
                }
                if (g.ModPow(phi_n.Divide(b), n).Equals(BigInteger.One))
                {
#if !NETFX_CORE
                    if (debug)
                    {
                        Console.WriteLine("g has order phi(n)/b\n g: " + g);
                    }
#endif
                    continue;
                }
                break;
            }
#if !NETFX_CORE
            if (debug)
            {
                Console.WriteLine("needed " + tries + " tries to generate g");
                Console.WriteLine();
                Console.WriteLine("found new NaccacheStern cipher variables:");
                Console.WriteLine("smallPrimes: " + CollectionUtilities.ToString(smallPrimes));
                Console.WriteLine("sigma:...... " + sigma + " (" + sigma.BitLength + " bits)");
                Console.WriteLine("a:.......... " + a);
                Console.WriteLine("b:.......... " + b);
                Console.WriteLine("p':......... " + _p);
                Console.WriteLine("q':......... " + _q);
                Console.WriteLine("p:.......... " + p);
                Console.WriteLine("q:.......... " + q);
                Console.WriteLine("n:.......... " + n);
                Console.WriteLine("phi(n):..... " + phi_n);
                Console.WriteLine("g:.......... " + g);
                Console.WriteLine();
            }
#endif

            return(new AsymmetricCipherKeyPair(new NaccacheSternKeyParameters(false, g, n, sigma.BitLength),
                                               new NaccacheSternPrivateKeyParameters(g, n, sigma.BitLength, smallPrimes, phi_n)));
        }