/** @com.intel.drl.spec_ref */
  public ECFieldF2m(int m, BigInteger rp) {
    this.m = m;
    if (this.m <= 0) {
      throw new IllegalArgumentException(Messages.getString("security.75")); // $NON-NLS-1$
    }
    this.rp = rp;
    if (this.rp == null) {
      throw new NullPointerException(Messages.getString("security.76")); // $NON-NLS-1$
    }
    // the leftmost bit must be (m+1)-th one,
    // set bits count must be 3 or 5,
    // bits 0 and m must be set
    int rp_bc = this.rp.bitCount();
    if ((this.rp.bitLength() != (m + 1))
        || (rp_bc != TPB_LEN && rp_bc != PPB_LEN)
        || (!this.rp.testBit(0) || !this.rp.testBit(m))) {
      throw new IllegalArgumentException(Messages.getString("security.77")); // $NON-NLS-1$
    }

    // setup ks using rp:
    // allocate for mid terms only
    ks = new int[rp_bc - 2];
    // find midterm orders and set ks accordingly
    BigInteger rpTmp = rp.clearBit(0);
    for (int i = ks.length - 1; i >= 0; i--) {
      ks[i] = rpTmp.getLowestSetBit();
      rpTmp = rpTmp.clearBit(ks[i]);
    }
  }
  private static BigInteger[] LucasSequence(
      BigInteger p, BigInteger X, BigInteger Y, BigInteger k) {
    int n = k.bitLength();
    int s = k.getLowestSetBit();

    BigInteger D = X.multiply(X).subtract(Y.shiftLeft(2));
    BigInteger U = BigInteger.ONE;
    BigInteger V = X;
    for (int j = n - 1; j >= s; j--) {
      if (k.testBit(j)) {
        BigInteger T = X.multiply(U).add(V).shiftRight(1).mod(p);
        V = X.multiply(V).add(D.multiply(U)).shiftRight(1).mod(p);
        U = T;
      } else {
        BigInteger T = U.multiply(V).mod(p);
        V = V.multiply(V).add(D.multiply(U.multiply(U))).shiftRight(1).mod(p);
        U = T;
      }
    }
    for (int j = 1; j <= s; j++) {
      BigInteger T = U.multiply(V).mod(p);
      V = V.multiply(V).add(D.multiply(U.multiply(U))).shiftRight(1).mod(p);
      U = T;
    }
    return new BigInteger[] {U, V};
  }
Exemple #3
0
  /**
   * Returns a BigDecimal representation of this fraction. If possible, the returned value will be
   * exactly equal to the fraction. If not, the BigDecimal will have a scale large enough to hold
   * the same number of significant figures as both numerator and denominator, or the equivalent of
   * a double-precision number, whichever is more.
   */
  public BigDecimal toBigDecimal() {
    // Implementation note:  A fraction can be represented exactly in base-10 iff its
    // denominator is of the form 2^a * 5^b, where a and b are nonnegative integers.
    // (In other words, if there are no prime factors of the denominator except for
    // 2 and 5, or if the denominator is 1).  So to determine if this denominator is
    // of this form, continually divide by 2 to get the number of 2's, and then
    // continually divide by 5 to get the number of 5's.  Afterward, if the denominator
    // is 1 then there are no other prime factors.

    // Note: number of 2's is given by the number of trailing 0 bits in the number
    int twos = denominator.getLowestSetBit();
    BigInteger tmpDen = denominator.shiftRight(twos); // x / 2^n === x >> n

    final BigInteger FIVE = BigInteger.valueOf(5);
    int fives = 0;
    BigInteger[] divMod = null;

    // while(tmpDen % 5 == 0) { fives++; tmpDen /= 5; }
    while (BigInteger.ZERO.equals((divMod = tmpDen.divideAndRemainder(FIVE))[1])) {
      fives++;
      tmpDen = divMod[0];
    }

    if (BigInteger.ONE.equals(tmpDen)) {
      // This fraction will terminate in base 10, so it can be represented exactly as
      // a BigDecimal.  We would now like to make the fraction of the form
      // unscaled / 10^scale.  We know that 2^x * 5^x = 10^x, and our denominator is
      // in the form 2^twos * 5^fives.  So use max(twos, fives) as the scale, and
      // multiply the numerator and deminator by the appropriate number of 2's or 5's
      // such that the denominator is of the form 2^scale * 5^scale.  (Of course, we
      // only have to actually multiply the numerator, since all we need for the
      // BigDecimal constructor is the scale.
      BigInteger unscaled = numerator;
      int scale = Math.max(twos, fives);

      if (twos < fives) unscaled = unscaled.shiftLeft(fives - twos); // x * 2^n === x << n
      else if (fives < twos) unscaled = unscaled.multiply(FIVE.pow(twos - fives));

      return new BigDecimal(unscaled, scale);
    }

    // else: this number will repeat infinitely in base-10.  So try to figure out
    // a good number of significant digits.  Start with the number of digits required
    // to represent the numerator and denominator in base-10, which is given by
    // bitLength / log[2](10).  (bitLenth is the number of digits in base-2).
    final double LG10 = 3.321928094887362; // Precomputed ln(10)/ln(2), a.k.a. log[2](10)
    int precision = Math.max(numerator.bitLength(), denominator.bitLength());
    precision = (int) Math.ceil(precision / LG10);

    // If the precision is less than 18 digits, use 18 digits so that the number
    // will be at least as accurate as a cast to a double.  For example, with
    // the fraction 1/3, precision will be 1, giving a result of 0.3.  This is
    // quite a bit different from what a user would expect.
    if (precision < 18) precision = 18;

    return toBigDecimal(precision);
  }
Exemple #4
0
  public BigInteger fastPower(BigInteger a, BigInteger t) {
    BigInteger result = BigInteger.ONE;
    while (t.compareTo(BigInteger.ZERO) == 1) {
      if (t.getLowestSetBit() == 0) {
        result = result.multiply(a);
      }

      a = a.multiply(a);
      t = t.shiftRight(1);
      a = a.mod(n);
      result = result.mod(n);
    }
    return result;
  }
  /**
   * Encodes a string using arithmetic encoding.
   *
   * @param message the message to encode
   * @return the encoded value as a byte array
   */
  @Override
  public byte[] encode(String message) {
    // Remove invalid UTF-8 symbols.
    message = message.replace(Character.toString((char) 0xFFFD), "");

    // Set up encoding process.
    BigInteger lowValue = BigInteger.valueOf(0);
    BigInteger highValue = BigInteger.valueOf(0);
    BigInteger length = BigInteger.valueOf(message.length());
    BigInteger totalProduct = BigInteger.valueOf(1);

    // Make the key based on the current string.
    CharMap key = makeKey(message);

    // Calculate the lowValue (the lowest possible encoding).
    for (Character c : message.toCharArray()) {
      lowValue = lowValue.add(totalProduct.multiply(BigInteger.valueOf(key.get(c))));
      lowValue = lowValue.multiply(length);
      totalProduct = totalProduct.multiply(BigInteger.valueOf(key.getProbability(c)));
    }
    lowValue = lowValue.divide(length);

    // Calculate the highValue based on the lowValue.
    highValue = lowValue.add(totalProduct);

    // Create a value for the final encoding
    BigInteger value = lowValue;
    value = maxZeroes(value, highValue);
    int zeroes = value.getLowestSetBit();
    value = value.shiftRight(zeroes);

    // Output the resulting number to a byte array.
    ByteArrayOutputStream outputBytes = new ByteArrayOutputStream();
    DataOutputStream output = new DataOutputStream(outputBytes);
    try {
      output.writeInt(key.size());
      output.writeInt(zeroes);
      for (Map.Entry<Character, Integer> e : key.entrySet()) {
        output.writeChar(e.getKey());
        output.writeInt(e.getValue());
      }
      output.write(value.toByteArray());
    } catch (java.io.IOException e) {
      System.err.println("There was an IOException.");
      return null;
    }

    // Return the output bytes.
    return outputBytes.toByteArray();
  }
Exemple #6
0
  /** Constructs a new BigFraction from the given BigDecimal object. */
  private static BigFraction valueOfHelper(final BigDecimal d) {
    // BigDecimal format: unscaled / 10^scale.
    BigInteger tmpNumerator = d.unscaledValue();
    BigInteger tmpDenominator = BigInteger.ONE;

    // Special case for d == 0 (math below won't work right)
    // Note: Cannot use d.equals(BigDecimal.ZERO), because
    // BigDecimal.equals()
    // does not consider numbers equal if they have different scales. So,
    // 0.00 is not equal to BigDecimal.ZERO.
    if (tmpNumerator.equals(BigInteger.ZERO)) {
      return BigFraction.ZERO;
    }

    if (d.scale() < 0) {
      tmpNumerator = tmpNumerator.multiply(BigInteger.TEN.pow(-d.scale()));
    } else if (d.scale() > 0) {
      // Now we have the form: unscaled / 10^scale = unscaled / (2^scale *
      // 5^scale)
      // We know then that gcd(unscaled, 2^scale * 5^scale) = 2^commonTwos
      // * 5^commonFives

      // Easy to determine commonTwos
      final int commonTwos = Math.min(d.scale(), tmpNumerator.getLowestSetBit());
      tmpNumerator = tmpNumerator.shiftRight(commonTwos);
      tmpDenominator = tmpDenominator.shiftLeft(d.scale() - commonTwos);

      // Determining commonFives is a little trickier..
      int commonFives = 0;

      BigInteger[] divMod = null;
      // while(commonFives < d.scale() && tmpNumerator % 5 == 0) {
      // tmpNumerator /= 5; commonFives++; }
      while (commonFives < d.scale()
          && BigInteger.ZERO.equals((divMod = tmpNumerator.divideAndRemainder(BIGINT_FIVE))[1])) {
        tmpNumerator = divMod[0];
        commonFives++;
      }

      if (commonFives < d.scale()) {
        tmpDenominator = tmpDenominator.multiply(BIGINT_FIVE.pow(d.scale() - commonFives));
      }
    }
    // else: d.scale() == 0: do nothing

    // Guaranteed there is no gcd, so fraction is in lowest terms
    return new BigFraction(tmpNumerator, tmpDenominator, Reduced.YES);
  }
    private BigInteger[] lucasSequence(BigInteger P, BigInteger Q, BigInteger k) {
      // TODO Research and apply "common-multiplicand multiplication here"

      int n = k.bitLength();
      int s = k.getLowestSetBit();

      // assert k.testBit(s);

      BigInteger Uh = ECConstants.ONE;
      BigInteger Vl = ECConstants.TWO;
      BigInteger Vh = P;
      BigInteger Ql = ECConstants.ONE;
      BigInteger Qh = ECConstants.ONE;

      for (int j = n - 1; j >= s + 1; --j) {
        Ql = modMult(Ql, Qh);

        if (k.testBit(j)) {
          Qh = modMult(Ql, Q);
          Uh = modMult(Uh, Vh);
          Vl = modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql)));
          Vh = modReduce(Vh.multiply(Vh).subtract(Qh.shiftLeft(1)));
        } else {
          Qh = Ql;
          Uh = modReduce(Uh.multiply(Vl).subtract(Ql));
          Vh = modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql)));
          Vl = modReduce(Vl.multiply(Vl).subtract(Ql.shiftLeft(1)));
        }
      }

      Ql = modMult(Ql, Qh);
      Qh = modMult(Ql, Q);
      Uh = modReduce(Uh.multiply(Vl).subtract(Ql));
      Vl = modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql)));
      Ql = modMult(Ql, Qh);

      for (int j = 1; j <= s; ++j) {
        Uh = modMult(Uh, Vl);
        Vl = modReduce(Vl.multiply(Vl).subtract(Ql.shiftLeft(1)));
        Ql = modMult(Ql, Ql);
      }

      return new BigInteger[] {Uh, Vl};
    }
    private static BigInteger[] lucasSequence(
        BigInteger p, BigInteger P, BigInteger Q, BigInteger k) {
      int n = k.bitLength();
      int s = k.getLowestSetBit();

      BigInteger Uh = ECConstants.ONE;
      BigInteger Vl = ECConstants.TWO;
      BigInteger Vh = P;
      BigInteger Ql = ECConstants.ONE;
      BigInteger Qh = ECConstants.ONE;

      for (int j = n - 1; j >= s + 1; --j) {
        Ql = Ql.multiply(Qh).mod(p);

        if (k.testBit(j)) {
          Qh = Ql.multiply(Q).mod(p);
          Uh = Uh.multiply(Vh).mod(p);
          Vl = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p);
          Vh = Vh.multiply(Vh).subtract(Qh.shiftLeft(1)).mod(p);
        } else {
          Qh = Ql;
          Uh = Uh.multiply(Vl).subtract(Ql).mod(p);
          Vh = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p);
          Vl = Vl.multiply(Vl).subtract(Ql.shiftLeft(1)).mod(p);
        }
      }

      Ql = Ql.multiply(Qh).mod(p);
      Qh = Ql.multiply(Q).mod(p);
      Uh = Uh.multiply(Vl).subtract(Ql).mod(p);
      Vl = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p);
      Ql = Ql.multiply(Qh).mod(p);

      for (int j = 1; j <= s; ++j) {
        Uh = Uh.multiply(Vl).mod(p);
        Vl = Vl.multiply(Vl).subtract(Ql.shiftLeft(1)).mod(p);
        Ql = Ql.multiply(Ql).mod(p);
      }

      return new BigInteger[] {Uh, Vl};
    }
  public static void bitOps(int order) {
    int failCount1 = 0, failCount2 = 0, failCount3 = 0;

    for (int i = 0; i < size * 5; i++) {
      BigInteger x = fetchNumber(order);
      BigInteger y;

      /* Test setBit and clearBit (and testBit) */
      if (x.signum() < 0) {
        y = BigInteger.valueOf(-1);
        for (int j = 0; j < x.bitLength(); j++) if (!x.testBit(j)) y = y.clearBit(j);
      } else {
        y = BigInteger.ZERO;
        for (int j = 0; j < x.bitLength(); j++) if (x.testBit(j)) y = y.setBit(j);
      }
      if (!x.equals(y)) failCount1++;

      /* Test flipBit (and testBit) */
      y = BigInteger.valueOf(x.signum() < 0 ? -1 : 0);
      for (int j = 0; j < x.bitLength(); j++) if (x.signum() < 0 ^ x.testBit(j)) y = y.flipBit(j);
      if (!x.equals(y)) failCount2++;
    }
    report("clearBit/testBit", failCount1);
    report("flipBit/testBit", failCount2);

    for (int i = 0; i < size * 5; i++) {
      BigInteger x = fetchNumber(order);

      /* Test getLowestSetBit() */
      int k = x.getLowestSetBit();
      if (x.signum() == 0) {
        if (k != -1) failCount3++;
      } else {
        BigInteger z = x.and(x.negate());
        int j;
        for (j = 0; j < z.bitLength() && !z.testBit(j); j++) ;
        if (k != j) failCount3++;
      }
    }
    report("getLowestSetBit", failCount3);
  }
Exemple #10
0
 /** Returns {@code true} if {@code x} represents a power of two. */
 public static boolean isPowerOfTwo(BigInteger x) {
   checkNotNull(x);
   return x.signum() > 0 && x.getLowestSetBit() == x.bitLength() - 1;
 }
Exemple #11
0
  /** Constructs a BigFraction from a floating-point number. */
  private static BigFraction valueOfHelper(final double d) {
    if (Double.isInfinite(d)) {
      throw new IllegalArgumentException("double val is infinite");
    }
    if (Double.isNaN(d)) {
      throw new IllegalArgumentException("double val is NaN");
    }

    // special case - math below won't work right for 0.0 or -0.0
    if (d == 0) {
      return BigFraction.ZERO;
    }

    // Per IEEE spec...
    final long bits = Double.doubleToLongBits(d);
    final int sign = (int) (bits >> 63) & 0x1;
    final int exponent = ((int) (bits >> 52) & 0x7ff) - 0x3ff;
    final long mantissa = bits & 0xfffffffffffffL;

    // Number is: (-1)^sign * 2^(exponent) * 1.mantissa
    // Neglecting sign bit, this gives:
    // 2^(exponent) * 1.mantissa
    // = 2^(exponent) * (1 + mantissa/2^52)
    // = 2^(exponent) * (2^52 + mantissa)/2^52
    // For exponent > 52:
    // = 2^(exponent - 52) * (2^52 + mantissa)
    // For exponent = 52:
    // = 2^52 + mantissa
    // For exponent < 52:
    // = (2^52 + mantissa) / 2^(52 - exponent)

    BigInteger tmpNumerator = BigInteger.valueOf(0x10000000000000L + mantissa);
    BigInteger tmpDenominator = BigInteger.ONE;

    if (exponent > 52) {
      // numerator * 2^(exponent - 52) === numerator << (exponent - 52)
      tmpNumerator = tmpNumerator.shiftLeft(exponent - 52);
    } else if (exponent < 52) {
      // The gcd of (2^52 + mantissa) / 2^(52 - exponent) must be of the
      // form 2^y,
      // since the only prime factors of the denominator are 2. In base-2,
      // it is
      // easy to determine how many factors of 2 a number has--it is the
      // number of
      // trailing "0" bits at the end of the number. (This is the same as
      // the number
      // of trailing 0's of a base-10 number indicating the number of
      // factors of 10
      // the number has).
      final int y = Math.min(tmpNumerator.getLowestSetBit(), 52 - exponent);

      // Now 2^y = gcd( 2^52 + mantissa, 2^(52 - exponent) ), giving:
      // (2^52 + mantissa) / 2^(52 - exponent)
      // = ((2^52 + mantissa) / 2^y) / (2^(52 - exponent) / 2^y)
      // = ((2^52 + mantissa) / 2^y) / (2^(52 - exponent - y))
      // = ((2^52 + mantissa) >> y) / (1 << (52 - exponent - y))
      tmpNumerator = tmpNumerator.shiftRight(y);
      tmpDenominator = tmpDenominator.shiftLeft(52 - exponent - y);
    }
    // else: exponent == 52: do nothing

    // Set sign bit if needed
    if (sign != 0) {
      tmpNumerator = tmpNumerator.negate();
    }

    // Guaranteed there is no gcd, so fraction is in lowest terms
    return new BigFraction(tmpNumerator, tmpDenominator, Reduced.YES);
  }