Exemplo n.º 1
0
        /**
         * Generate a signature for the given message using the key we were
         * initialised with. For conventional DSA the message should be a SHA-1
         * hash of the message of interest.
         *
         * @param message the message that will be verified later.
         */
        public virtual BigInteger[] GenerateSignature(byte[] message)
        {
            DsaParameters parameters = key.Parameters;
            BigInteger    q          = parameters.Q;
            BigInteger    m          = CalculateE(q, message);
            BigInteger    x          = ((DsaPrivateKeyParameters)key).X;

            if (kCalculator.IsDeterministic)
            {
                kCalculator.Init(q, x, message);
            }
            else
            {
                kCalculator.Init(q, random);
            }

            BigInteger k = kCalculator.NextK();

            BigInteger r = parameters.G.ModPow(k, parameters.P).Mod(q);

            k = BigIntegers.ModOddInverse(q, k).Multiply(m.Add(x.Multiply(r)));

            BigInteger s = k.Mod(q);

            return(new BigInteger[] { r, s });
        }
        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(BigIntegers.ModOddInverse(q, p));

            this.expP = d.Remainder(p.Subtract(BigInteger.One));
            this.expQ = d.Remainder(q.Subtract(BigInteger.One));
            this.crt  = BigIntegers.ModOddInverse(p, q);
        }
Exemplo n.º 3
0
        /*
         * Unblind the message blinded with the blind factor.
         */
        private BigInteger UnblindMessage(
            BigInteger blindedMsg)
        {
            BigInteger m   = key.Modulus;
            BigInteger msg = blindedMsg;
            BigInteger blindFactorInverse = BigIntegers.ModOddInverse(m, blindingFactor);

            msg = msg.Multiply(blindFactorInverse);
            msg = msg.Mod(m);

            return(msg);
        }
        public RsaSecretBcpgKey(
            BcpgInputStream bcpgIn)
        {
            this.d = new MPInteger(bcpgIn);
            this.p = new MPInteger(bcpgIn);
            this.q = new MPInteger(bcpgIn);
            this.u = new MPInteger(bcpgIn);

            this.expP = d.Value.Remainder(p.Value.Subtract(BigInteger.One));
            this.expQ = d.Value.Remainder(q.Value.Subtract(BigInteger.One));
            this.crt  = BigIntegers.ModOddInverse(p.Value, q.Value);
        }
        /**
         * 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 virtual byte[] ProcessBlock(
            byte[] inBuf,
            int inOff,
            int inLen)
        {
            if (key == null)
            {
                throw new InvalidOperationException("RSA engine not initialised");
            }

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

            BigInteger result;

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

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

                    BigInteger rInv = BigIntegers.ModOddInverse(m, r);
                    result = blindedResult.Multiply(rInv).Mod(m);

                    // defence against Arjen Lenstra’s CRT attack
                    if (!input.Equals(result.ModPow(e, m)))
                    {
                        throw new InvalidOperationException("RSA engine faulty decryption/signing detected");
                    }
                }
                else
                {
                    result = core.ProcessBlock(input);
                }
            }
            else
            {
                result = core.ProcessBlock(input);
            }

            return(core.ConvertOutput(result));
        }
Exemplo n.º 6
0
        public virtual byte[] GenerateSignature()
        {
            byte[] eHash = DigestUtilities.DoFinal(digest);

            BigInteger n = ecParams.N;
            BigInteger e = CalculateE(n, eHash);
            BigInteger d = ((ECPrivateKeyParameters)ecKey).D;

            BigInteger r, s;

            ECMultiplier basePointMultiplier = CreateBasePointMultiplier();

            // 5.2.1 Draft RFC:  SM2 Public Key Algorithms
            do // generate s
            {
                BigInteger k;
                do // generate r
                {
                    // A3
                    k = kCalculator.NextK();

                    // A4
                    ECPoint p = basePointMultiplier.Multiply(ecParams.G, k).Normalize();

                    // A5
                    r = e.Add(p.AffineXCoord.ToBigInteger()).Mod(n);
                }while (r.SignValue == 0 || r.Add(k).Equals(n));

                // A6
                BigInteger dPlus1ModN = BigIntegers.ModOddInverse(n, d.Add(BigIntegers.One));

                s = k.Subtract(r.Multiply(d)).Mod(n);
                s = dPlus1ModN.Multiply(s).Mod(n);
            }while (s.SignValue == 0);

            // A7
            try
            {
                return(encoding.Encode(ecParams.N, r, s));
            }
            catch (Exception ex)
            {
                throw new CryptoException("unable to encode signature: " + ex.Message, ex);
            }
        }
        // 5.3 pg 28

        /**
         * Generate a signature for the given message using the key we were
         * initialised with. For conventional DSA the message should be a SHA-1
         * hash of the message of interest.
         *
         * @param message the message that will be verified later.
         */
        public virtual BigInteger[] GenerateSignature(byte[] message)
        {
            ECDomainParameters ec = key.Parameters;
            BigInteger         n  = ec.N;
            BigInteger         e  = CalculateE(n, message);
            BigInteger         d  = ((ECPrivateKeyParameters)key).D;

            if (kCalculator.IsDeterministic)
            {
                kCalculator.Init(n, d, message);
            }
            else
            {
                kCalculator.Init(n, random);
            }

            BigInteger r, s;

            ECMultiplier basePointMultiplier = CreateBasePointMultiplier();

            // 5.3.2
            do // Generate s
            {
                BigInteger k;
                do // Generate r
                {
                    k = kCalculator.NextK();

                    ECPoint p = basePointMultiplier.Multiply(ec.G, k).Normalize();

                    // 5.3.3
                    r = p.AffineXCoord.ToBigInteger().Mod(n);
                }while (r.SignValue == 0);

                s = BigIntegers.ModOddInverse(n, k).Multiply(e.Add(d.Multiply(r))).Mod(n);
            }while (s.SignValue == 0);

            return(new BigInteger[] { r, s });
        }
Exemplo n.º 8
0
 protected virtual BigInteger ModInverse(BigInteger x)
 {
     return(BigIntegers.ModOddInverse(q, x));
 }
        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 = BigIntegers.ModOddInverse(p, q);

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