Exemplo n.º 1
0
        /**
         * It requires that all parameters be positive.
         *
         * @return {@code base<sup>exponent</sup> mod (2<sup>j</sup>)}.
         * @see BigInteger#modPow(BigInteger, BigInteger)
         */

        private static BigInteger Pow2ModPow(BigInteger b, BigInteger exponent, int j)
        {
            // PRE: (base > 0), (exponent > 0) and (j > 0)
            BigInteger res         = BigInteger.One;
            BigInteger e           = exponent.Copy();
            BigInteger baseMod2toN = b.Copy();
            BigInteger res2;

            /*
             * If 'base' is odd then it's coprime with 2^j and phi(2^j) = 2^(j-1);
             * so we can reduce reduce the exponent (mod 2^(j-1)).
             */
            if (BigInteger.TestBit(b, 0))
            {
                InplaceModPow2(e, j - 1);
            }
            InplaceModPow2(baseMod2toN, j);

            for (int i = e.BitLength - 1; i >= 0; i--)
            {
                res2 = res.Copy();
                InplaceModPow2(res2, j);
                res = res * res2;
                if (BitLevel.TestBit(e, i))
                {
                    res = res * baseMod2toN;
                    InplaceModPow2(res, j);
                }
            }
            InplaceModPow2(res, j);
            return(res);
        }
Exemplo n.º 2
0
        /**
         *  Performs a<sup>2</sup>
         *  @param a The number to square.
         *  @param aLen The length of the number to square.
         */
        static int[] square(int[] a, int aLen, int[] res)
        {
            long carry;

            for (int i = 0; i < aLen; i++)
            {
                carry = 0;
                for (int j = i + 1; j < aLen; j++)
                {
                    carry      = unsignedMultAddAdd(a[i], a[j], res[i + j], (int)carry);
                    res[i + j] = (int)carry;
                    carry      = Utils.URShift(carry, 32);
                }
                res[i + aLen] = (int)carry;
            }

            BitLevel.shiftLeftOneBit(res, res, aLen << 1);

            carry = 0;
            for (int i = 0, index = 0; i < aLen; i++, index++)
            {
                carry      = unsignedMultAddAdd(a[i], a[i], res[index], (int)carry);
                res[index] = (int)carry;
                carry      = Utils.URShift(carry, 32);
                index++;
                carry     += res[index] & 0xFFFFFFFFL;
                res[index] = (int)carry;
                carry      = Utils.URShift(carry, 32);
            }
            return(res);
        }
Exemplo n.º 3
0
 /**
  * Returns a new {@code BigInteger} which has the same binary representation
  * as {@code this} but with the bit at position n cleared. The result is
  * equivalent to {@code this & ~(2^n)}.
  * <p>
  * <b>Implementation Note:</b> Usage of this method is not recommended as
  * the current implementation is not efficient.
  *
  * @param n
  *            position where the bit in {@code this} has to be cleared.
  * @return {@code this & ~(2^n)}.
  * @throws ArithmeticException
  *             if {@code n < 0}.
  */
 public static BigInteger ClearBit(BigInteger value, int n)
 {
     if (TestBit(value, n))
     {
         return(BitLevel.FlipBit(value, n));
     }
     return(value);
 }
Exemplo n.º 4
0
 public static BigInteger ShiftLeft(BigInteger value, int n)
 {
     if ((n == 0) || (value.Sign == 0))
     {
         return(value);
     }
     return((n > 0) ? BitLevel.ShiftLeft(value, n) : BitLevel.ShiftRight(value, -n));
 }
Exemplo n.º 5
0
 /**
  * Returns a new {@code BigInteger} which has the same binary representation
  * as {@code this} but with the bit at position n flipped. The result is
  * equivalent to {@code this ^ 2^n}.
  * <p>
  * <b>Implementation Note:</b> Usage of this method is not recommended as
  * the current implementation is not efficient.
  *
  * @param n
  *            position where the bit in {@code this} has to be flipped.
  * @return {@code this ^ 2^n}.
  * @throws ArithmeticException
  *             if {@code n < 0}.
  */
 public static BigInteger FlipBit(BigInteger value, int n)
 {
     if (n < 0)
     {
         // math.15=Negative bit address
         throw new ArithmeticException(Messages.math15); //$NON-NLS-1$
     }
     return(BitLevel.FlipBit(value, n));
 }
Exemplo n.º 6
0
        /** @see BigInteger#ToDouble() */

        public static double BigInteger2Double(BigInteger val)
        {
            // val.bitLength() < 64
            if ((val.numberLength < 2) ||
                ((val.numberLength == 2) && (val.Digits[1] > 0)))
            {
                return(val.ToInt64());
            }
            // val.bitLength() >= 33 * 32 > 1024
            if (val.numberLength > 32)
            {
                return((val.Sign > 0) ? Double.PositiveInfinity
                                                : Double.NegativeInfinity);
            }
            int  bitLen   = BigMath.Abs(val).BitLength;
            long exponent = bitLen - 1;
            int  delta    = bitLen - 54;
            // We need 54 top bits from this, the 53th bit is always 1 in lVal.
            long lVal = (BigMath.Abs(val) >> delta).ToInt64();

            /*
             * Take 53 bits from lVal to mantissa. The least significant bit is
             * needed for rounding.
             */
            long mantissa = lVal & 0x1FFFFFFFFFFFFFL;

            if (exponent == 1023)
            {
                if (mantissa == 0X1FFFFFFFFFFFFFL)
                {
                    return((val.Sign > 0) ? Double.PositiveInfinity
                                                        : Double.NegativeInfinity);
                }
                if (mantissa == 0x1FFFFFFFFFFFFEL)
                {
                    return((val.Sign > 0) ? Double.MaxValue : -Double.MaxValue);
                }
            }
            // Round the mantissa
            if (((mantissa & 1) == 1) &&
                (((mantissa & 2) == 2) || BitLevel.NonZeroDroppedBits(delta,
                                                                      val.Digits)))
            {
                mantissa += 2;
            }
            mantissa >>= 1;             // drop the rounding bit
            // long resSign = (val.sign < 0) ? 0x8000000000000000L : 0;
            long resSign = (val.Sign < 0) ? Int64.MinValue : 0;

            exponent = ((1023 + exponent) << 52) & 0x7FF0000000000000L;
            long result = resSign | exponent | mantissa;

            return(BitConverter.Int64BitsToDouble(result));
        }
Exemplo n.º 7
0
        /*Implements the Montgomery modular exponentiation based in <i>The sliding windows algorithm and the Mongomery
         * Reduction</i>.
         *@ar.org.fitc.ref "A. Menezes,P. van Oorschot, S. Vanstone - Handbook of Applied Cryptography";
         *@see #oddModPow(BigInteger, BigInteger,
         *                           BigInteger)
         */

        private static BigInteger SlidingWindow(BigInteger x2, BigInteger a2, BigInteger exponent, BigInteger modulus, int n2)
        {
            // fill odd low pows of a2
            BigInteger[] pows = new BigInteger[8];
            BigInteger   res  = x2;
            int          lowexp;
            BigInteger   x3;
            int          acc3;

            pows[0] = a2;

            x3 = MonPro(a2, a2, modulus, n2);
            for (int i = 1; i <= 7; i++)
            {
                pows[i] = MonPro(pows[i - 1], x3, modulus, n2);
            }

            for (int i = exponent.BitLength - 1; i >= 0; i--)
            {
                if (BitLevel.TestBit(exponent, i))
                {
                    lowexp = 1;
                    acc3   = i;

                    for (int j = System.Math.Max(i - 3, 0); j <= i - 1; j++)
                    {
                        if (BitLevel.TestBit(exponent, j))
                        {
                            if (j < acc3)
                            {
                                acc3   = j;
                                lowexp = (lowexp << (i - j)) ^ 1;
                            }
                            else
                            {
                                lowexp = lowexp ^ (1 << (j - acc3));
                            }
                        }
                    }

                    for (int j = acc3; j <= i; j++)
                    {
                        res = MonPro(res, res, modulus, n2);
                    }
                    res = MonPro(pows[(lowexp - 1) >> 1], res, modulus, n2);
                    i   = acc3;
                }
                else
                {
                    res = MonPro(res, res, modulus, n2);
                }
            }
            return(res);
        }
Exemplo n.º 8
0
        private static BigInteger SquareAndMultiply(BigInteger x2, BigInteger a2, BigInteger exponent, BigInteger modulus, int n2)
        {
            BigInteger res = x2;

            for (int i = exponent.BitLength - 1; i >= 0; i--)
            {
                res = MonPro(res, res, modulus, n2);
                if (BitLevel.TestBit(exponent, i))
                {
                    res = MonPro(res, a2, modulus, n2);
                }
            }
            return(res);
        }
Exemplo n.º 9
0
        /**
         * @param x an odd positive number.
         * @param n the exponent by which 2 is raised.
         * @return {@code x<sup>-1</sup> (mod 2<sup>n</sup>)}.
         */

        private static BigInteger ModPow2Inverse(BigInteger x, int n)
        {
            // PRE: (x > 0), (x is odd), and (n > 0)
            BigInteger y = new BigInteger(1, new int[1 << n]);

            y.numberLength = 1;
            y.Digits[0]    = 1;
            y.Sign         = 1;

            for (int i = 1; i < n; i++)
            {
                if (BitLevel.TestBit(x * y, i))
                {
                    // Adding 2^i to y (setting the i-th bit)
                    y.Digits[i >> 5] |= (1 << (i & 31));
                }
            }
            return(y);
        }
Exemplo n.º 10
0
 internal BigInteger ShiftLeftOneBit()
 {
     return((sign == 0) ? this : BitLevel.ShiftLeftOneBit(this));
 }
Exemplo n.º 11
0
        /**
         *
         * Based on "New Algorithm for Classical Modular Inverse" Róbert Lórencz.
         * LNCS 2523 (2002)
         *
         * @return a^(-1) mod m
         */

        private static BigInteger ModInverseLorencz(BigInteger a, BigInteger modulo)
        {
            // PRE: a is coprime with modulo, a < modulo

            int max = System.Math.Max(a.numberLength, modulo.numberLength);

            int[] uDigits = new int[max + 1];             // enough place to make all the inplace operation
            int[] vDigits = new int[max + 1];
            Array.Copy(modulo.Digits, 0, uDigits, 0, modulo.numberLength);
            Array.Copy(a.Digits, 0, vDigits, 0, a.numberLength);
            BigInteger u = new BigInteger(modulo.Sign,
                                          modulo.numberLength,
                                          uDigits);
            BigInteger v = new BigInteger(a.Sign, a.numberLength, vDigits);

            BigInteger r = new BigInteger(0, 1, new int[max + 1]);             // BigInteger.ZERO;
            BigInteger s = new BigInteger(1, 1, new int[max + 1]);

            s.Digits[0] = 1;
            // r == 0 && s == 1, but with enough place

            int coefU = 0, coefV = 0;
            int n = modulo.BitLength;
            int k;

            while (!IsPowerOfTwo(u, coefU) && !IsPowerOfTwo(v, coefV))
            {
                // modification of original algorithm: I calculate how many times the algorithm will enter in the same branch of if
                k = HowManyIterations(u, n);

                if (k != 0)
                {
                    BitLevel.InplaceShiftLeft(u, k);
                    if (coefU >= coefV)
                    {
                        BitLevel.InplaceShiftLeft(r, k);
                    }
                    else
                    {
                        BitLevel.InplaceShiftRight(s, System.Math.Min(coefV - coefU, k));
                        if (k - (coefV - coefU) > 0)
                        {
                            BitLevel.InplaceShiftLeft(r, k - coefV + coefU);
                        }
                    }
                    coefU += k;
                }

                k = HowManyIterations(v, n);
                if (k != 0)
                {
                    BitLevel.InplaceShiftLeft(v, k);
                    if (coefV >= coefU)
                    {
                        BitLevel.InplaceShiftLeft(s, k);
                    }
                    else
                    {
                        BitLevel.InplaceShiftRight(r, System.Math.Min(coefU - coefV, k));
                        if (k - (coefU - coefV) > 0)
                        {
                            BitLevel.InplaceShiftLeft(s, k - coefU + coefV);
                        }
                    }
                    coefV += k;
                }

                if (u.Sign == v.Sign)
                {
                    if (coefU <= coefV)
                    {
                        Elementary.completeInPlaceSubtract(u, v);
                        Elementary.completeInPlaceSubtract(r, s);
                    }
                    else
                    {
                        Elementary.completeInPlaceSubtract(v, u);
                        Elementary.completeInPlaceSubtract(s, r);
                    }
                }
                else
                {
                    if (coefU <= coefV)
                    {
                        Elementary.completeInPlaceAdd(u, v);
                        Elementary.completeInPlaceAdd(r, s);
                    }
                    else
                    {
                        Elementary.completeInPlaceAdd(v, u);
                        Elementary.completeInPlaceAdd(s, r);
                    }
                }
                if (v.Sign == 0 || u.Sign == 0)
                {
                    // math.19: BigInteger not invertible
                    throw new ArithmeticException(Messages.math19);
                }
            }

            if (IsPowerOfTwo(v, coefV))
            {
                r = s;
                if (v.Sign != u.Sign)
                {
                    u = -u;
                }
            }
            if (BigInteger.TestBit(u, n))
            {
                if (r.Sign < 0)
                {
                    r = -r;
                }
                else
                {
                    r = modulo - r;
                }
            }
            if (r.Sign < 0)
            {
                r += modulo;
            }

            return(r);
        }
Exemplo n.º 12
0
        /**
         * Calculates a.modInverse(p) Based on: Savas, E; Koc, C "The Montgomery Modular
         * Inverse - Revised"
         */

        public static BigInteger ModInverseMontgomery(BigInteger a, BigInteger p)
        {
            if (a.Sign == 0)
            {
                // ZERO hasn't inverse
                // math.19: BigInteger not invertible
                throw new ArithmeticException(Messages.math19);
            }

            if (!BigInteger.TestBit(p, 0))
            {
                // montgomery inverse require even modulo
                return(ModInverseLorencz(a, p));
            }

            int m = p.numberLength * 32;
            // PRE: a \in [1, p - 1]
            BigInteger u, v, r, s;

            u = p.Copy();             // make copy to use inplace method
            v = a.Copy();
            int max = System.Math.Max(v.numberLength, u.numberLength);

            r           = new BigInteger(1, 1, new int[max + 1]);
            s           = new BigInteger(1, 1, new int[max + 1]);
            s.Digits[0] = 1;
            // s == 1 && v == 0

            int k = 0;

            int lsbu = u.LowestSetBit;
            int lsbv = v.LowestSetBit;
            int toShift;

            if (lsbu > lsbv)
            {
                BitLevel.InplaceShiftRight(u, lsbu);
                BitLevel.InplaceShiftRight(v, lsbv);
                BitLevel.InplaceShiftLeft(r, lsbv);
                k += lsbu - lsbv;
            }
            else
            {
                BitLevel.InplaceShiftRight(u, lsbu);
                BitLevel.InplaceShiftRight(v, lsbv);
                BitLevel.InplaceShiftLeft(s, lsbu);
                k += lsbv - lsbu;
            }

            r.Sign = 1;
            while (v.Sign > 0)
            {
                // INV v >= 0, u >= 0, v odd, u odd (except last iteration when v is even (0))

                while (u.CompareTo(v) > BigInteger.EQUALS)
                {
                    Elementary.inplaceSubtract(u, v);
                    toShift = u.LowestSetBit;
                    BitLevel.InplaceShiftRight(u, toShift);
                    Elementary.inplaceAdd(r, s);
                    BitLevel.InplaceShiftLeft(s, toShift);
                    k += toShift;
                }

                while (u.CompareTo(v) <= BigInteger.EQUALS)
                {
                    Elementary.inplaceSubtract(v, u);
                    if (v.Sign == 0)
                    {
                        break;
                    }
                    toShift = v.LowestSetBit;
                    BitLevel.InplaceShiftRight(v, toShift);
                    Elementary.inplaceAdd(s, r);
                    BitLevel.InplaceShiftLeft(r, toShift);
                    k += toShift;
                }
            }
            if (!u.IsOne)
            {
                // in u is stored the gcd
                // math.19: BigInteger not invertible.
                throw new ArithmeticException(Messages.math19);
            }
            if (r.CompareTo(p) >= BigInteger.EQUALS)
            {
                Elementary.inplaceSubtract(r, p);
            }

            r = p - r;

            // Have pair: ((BigInteger)r, (Integer)k) where r == a^(-1) * 2^k mod (module)
            int n1 = CalcN(p);

            if (k > m)
            {
                r = MonPro(r, BigInteger.One, p, n1);
                k = k - m;
            }

            r = MonPro(r, BigInteger.GetPowerOfTwo(m - k), p, n1);
            return(r);
        }
Exemplo n.º 13
0
        /**
         * Divides the array 'a' by the array 'b' and gets the quotient and the
         * remainder. Implements the Knuth's division algorithm. See D. Knuth, The
         * Art of Computer Programming, vol. 2. Steps D1-D8 correspond the steps in
         * the algorithm description.
         *
         * @param quot the quotient
         * @param quotLength the quotient's length
         * @param a the dividend
         * @param aLength the dividend's length
         * @param b the divisor
         * @param bLength the divisor's length
         * @return the remainder
         */

        public static int[] Divide(int[] quot, int quotLength, int[] a, int aLength, int[] b, int bLength)
        {
            int[] normA = new int[aLength + 1];             // the normalized dividend
            // an extra byte is needed for correct shift
            int[] normB       = new int[bLength + 1];       // the normalized divisor;
            int   normBLength = bLength;

            /*
             * Step D1: normalize a and b and put the results to a1 and b1 the
             * normalized divisor's first digit must be >= 2^31
             */
            int divisorShift = Utils.NumberOfLeadingZeros(b[bLength - 1]);

            if (divisorShift != 0)
            {
                BitLevel.ShiftLeft(normB, b, 0, divisorShift);
                BitLevel.ShiftLeft(normA, a, 0, divisorShift);
            }
            else
            {
                Array.Copy(a, 0, normA, 0, aLength);
                Array.Copy(b, 0, normB, 0, bLength);
            }
            int firstDivisorDigit = normB[normBLength - 1];
            // Step D2: set the quotient index
            int i = quotLength - 1;
            int j = aLength;

            while (i >= 0)
            {
                // Step D3: calculate a guess digit guessDigit
                int guessDigit = 0;
                if (normA[j] == firstDivisorDigit)
                {
                    // set guessDigit to the largest unsigned int value
                    guessDigit = -1;
                }
                else
                {
                    long product = (((normA[j] & 0xffffffffL) << 32) + (normA[j - 1] & 0xffffffffL));
                    long res     = Division.DivideLongByInt(product, firstDivisorDigit);
                    guessDigit = (int)res;                      // the quotient of divideLongByInt
                    int rem = (int)(res >> 32);                 // the remainder of
                    // divideLongByInt
                    // decrease guessDigit by 1 while leftHand > rightHand
                    if (guessDigit != 0)
                    {
                        long leftHand    = 0;
                        long rightHand   = 0;
                        bool rOverflowed = false;
                        guessDigit++;                         // to have the proper value in the loop
                        // below
                        do
                        {
                            guessDigit--;
                            if (rOverflowed)
                            {
                                break;
                            }
                            // leftHand always fits in an unsigned long
                            leftHand = (guessDigit & 0xffffffffL)
                                       * (normB[normBLength - 2] & 0xffffffffL);

                            /*
                             * rightHand can overflow; in this case the loop
                             * condition will be true in the next step of the loop
                             */
                            rightHand = ((long)rem << 32)
                                        + (normA[j - 2] & 0xffffffffL);
                            long longR = (rem & 0xffffffffL)
                                         + (firstDivisorDigit & 0xffffffffL);

                            /*
                             * checks that longR does not fit in an unsigned int;
                             * this ensures that rightHand will overflow unsigned
                             * long in the next step
                             */
                            if (Utils.NumberOfLeadingZeros((int)Utils.URShift(longR, 32)) < 32)
                            {
                                rOverflowed = true;
                            }
                            else
                            {
                                rem = (int)longR;
                            }
                        } while ((leftHand ^ Int64.MinValue) > (rightHand ^ Int64.MinValue));

                        //} while ((leftHand ^ Int64.MaxValue) > (rightHand ^ Int64.MaxValue));
                        // while (((leftHand ^ 0x8000000000000000L) > (rightHand ^ 0x8000000000000000L))) ;
                    }
                }
                // Step D4: multiply normB by guessDigit and subtract the production
                // from normA.
                if (guessDigit != 0)
                {
                    int borrow = Division.MultiplyAndSubtract(normA, j - normBLength, normB, normBLength, guessDigit);
                    // Step D5: check the borrow
                    if (borrow != 0)
                    {
                        // Step D6: compensating addition
                        guessDigit--;
                        long carry = 0;
                        for (int k = 0; k < normBLength; k++)
                        {
                            carry += (normA[j - normBLength + k] & 0xffffffffL)
                                     + (normB[k] & 0xffffffffL);
                            normA[j - normBLength + k] = (int)carry;
                            carry = Utils.URShift(carry, 32);
                        }
                    }
                }
                if (quot != null)
                {
                    quot[i] = guessDigit;
                }
                // Step D7
                j--;
                i--;
            }

            /*
             * Step D8: we got the remainder in normA. Denormalize it id needed
             */
            if (divisorShift != 0)
            {
                // reuse normB
                BitLevel.ShiftRight(normB, normBLength, normA, 0, divisorShift);
                return(normB);
            }
            Array.Copy(normA, 0, normB, 0, bLength);
            return(normA);
        }
Exemplo n.º 14
0
        /**
         * @param m a positive modulus
         * Return the greatest common divisor of op1 and op2,
         *
         * @param op1
         *            must be greater than zero
         * @param op2
         *            must be greater than zero
         * @see BigInteger#gcd(BigInteger)
         * @return {@code GCD(op1, op2)}
         */

        public static BigInteger GcdBinary(BigInteger op1, BigInteger op2)
        {
            // PRE: (op1 > 0) and (op2 > 0)

            /*
             * Divide both number the maximal possible times by 2 without rounding
             * gcd(2*a, 2*b) = 2 * gcd(a,b)
             */
            int lsb1      = op1.LowestSetBit;
            int lsb2      = op2.LowestSetBit;
            int pow2Count = System.Math.Min(lsb1, lsb2);

            BitLevel.InplaceShiftRight(op1, lsb1);
            BitLevel.InplaceShiftRight(op2, lsb2);

            BigInteger swap;

            // I want op2 > op1
            if (op1.CompareTo(op2) == BigInteger.GREATER)
            {
                swap = op1;
                op1  = op2;
                op2  = swap;
            }

            do
            {
                // INV: op2 >= op1 && both are odd unless op1 = 0

                // Optimization for small operands
                // (op2.bitLength() < 64) implies by INV (op1.bitLength() < 64)
                if ((op2.numberLength == 1) ||
                    ((op2.numberLength == 2) && (op2.Digits[1] > 0)))
                {
                    op2 = BigInteger.FromInt64(Division.GcdBinary(op1.ToInt64(),
                                                                  op2.ToInt64()));
                    break;
                }

                // Implements one step of the Euclidean algorithm
                // To reduce one operand if it's much smaller than the other one
                if (op2.numberLength > op1.numberLength * 1.2)
                {
                    op2 = BigMath.Remainder(op2, op1);
                    if (op2.Sign != 0)
                    {
                        BitLevel.InplaceShiftRight(op2, op2.LowestSetBit);
                    }
                }
                else
                {
                    // Use Knuth's algorithm of successive subtract and shifting
                    do
                    {
                        Elementary.inplaceSubtract(op2, op1);                         // both are odd
                        BitLevel.InplaceShiftRight(op2, op2.LowestSetBit);            // op2 is even
                    } while (op2.CompareTo(op1) >= BigInteger.EQUALS);
                }
                // now op1 >= op2
                swap = op2;
                op2  = op1;
                op1  = swap;
            } while (op1.Sign != 0);
            return(op2 << pow2Count);
        }