Example #1
0
  /**
   * Returns a byte-array representation of a <code>BigInteger</code> without sign bit.
   *
   * @param bigInt <code>BigInteger</code> to be converted
   * @return a byte array representation of the BigInteger parameter
   */
  static byte[] toIntegerBytes(BigInteger bigInt) {
    int bitlen = bigInt.bitLength();
    // round bitlen
    bitlen = ((bitlen + 7) >> 3) << 3;
    byte[] bigBytes = bigInt.toByteArray();

    if (((bigInt.bitLength() % 8) != 0) && (((bigInt.bitLength() / 8) + 1) == (bitlen / 8))) {
      return bigBytes;
    }

    // set up params for copying everything but sign bit
    int startSrc = 0;
    int len = bigBytes.length;

    // if bigInt is exactly byte-aligned, just skip signbit in copy
    if ((bigInt.bitLength() % 8) == 0) {
      startSrc = 1;
      len--;
    }

    int startDst = bitlen / 8 - len; // to pad w/ nulls as per spec
    byte[] resizedBytes = new byte[bitlen / 8];

    System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, len);

    return resizedBytes;
  }
Example #2
0
  public void initialize() {
    e = BigInteger.valueOf(65537);
    SecureRandom sr = new SecureRandom();

    BigInteger diff = BigInteger.valueOf(2).pow(256);

    /*
    generate 2 prime numbers greater than 512 bits and that have difference of 2^256
    */
    do {
      sr.generateSeed(size);
      p = new BigInteger(size, 256, sr);
      sr.generateSeed(size);
      q = new BigInteger(size, 256, sr);

    } while (p.bitLength() < size
        || q.bitLength() < size
        || !p.isProbablePrime(256)
        || !q.isProbablePrime(256)
        || p.subtract(q).abs().compareTo(diff) != 1);

    n = p.multiply(q);
    phi_n = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
    d = e.modInverse(phi_n);
  }
Example #3
0
  /**
   * Returns a byte-array representation of a <code>{@link BigInteger}<code>.
   * No sign-bit is output.
   *
   * <b>N.B.:</B> <code>{@link BigInteger}<code>'s toByteArray
   * returns eventually longer arrays because of the leading sign-bit.
   *
   * @param big <code>BigInteger<code> to be converted
   * @param bitlen <code>int<code> the desired length in bits of the representation
   * @return a byte array with <code>bitlen</code> bits of <code>big</code>
   */
  public static final byte[] encode(BigInteger big, int bitlen) {

    // round bitlen
    bitlen = ((bitlen + 7) >> 3) << 3;

    if (bitlen < big.bitLength()) {
      throw new IllegalArgumentException(I18n.translate("utils.Base64.IllegalBitlength"));
    }

    byte[] bigBytes = big.toByteArray();

    if (((big.bitLength() % 8) != 0) && (((big.bitLength() / 8) + 1) == (bitlen / 8))) {
      return bigBytes;
    }

    // some copying needed
    int startSrc = 0; // no need to skip anything
    int bigLen = bigBytes.length; // valid length of the string

    if ((big.bitLength() % 8) == 0) { // correct values
      startSrc = 1; // skip sign bit

      bigLen--; // valid length of the string
    }

    int startDst = bitlen / 8 - bigLen; // pad with leading nulls
    byte[] resizedBytes = new byte[bitlen / 8];

    System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, bigLen);

    return resizedBytes;
  }
Example #4
0
  public void Enc(String input_filename, String output_filename, String keystorename) {
    readKeystore(keystorename);
    buffer = new byte[n.bitLength() / 8 - (n.bitLength() % 8 == 0 ? 1 : 0)];
    int out_bytes = n.bitLength() / 8 + (n.bitLength() % 8 != 0 ? 1 : 0);

    FileInputStream input;
    FileOutputStream output;
    BigInteger number;
    try {
      input = new FileInputStream(input_filename);
      output = new FileOutputStream(output_filename);

      int bytes = 0;
      while ((bytes = input.read(buffer)) != -1) {
        if (bytes != buffer.length) for (int i = bytes; i < buffer.length; i++) buffer[i] = 0;
        number = new BigInteger(1, buffer);
        number = fastPower(number, e);
        byte[] num_bytes = number.toByteArray();
        if (num_bytes[0] == 0 && num_bytes.length != 1)
          num_bytes = Arrays.copyOfRange(num_bytes, 1, num_bytes.length);
        for (int i = 0; i < out_bytes - num_bytes.length; i++) output.write(new byte[] {0});
        output.write(num_bytes);
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  /** @tests java.math.BigInteger#andNot(java.math.BigInteger) */
  @TestTargetNew(
      level = TestLevel.COMPLETE,
      notes = "",
      method = "andNot",
      args = {java.math.BigInteger.class})
  public void test_andNotLjava_math_BigInteger() {
    for (BigInteger[] element : booleanPairs) {
      BigInteger i1 = element[0], i2 = element[1];
      BigInteger res = i1.andNot(i2);
      int len = Math.max(i1.bitLength(), i2.bitLength()) + 66;
      for (int i = 0; i < len; i++) {
        assertTrue("andNot", (i1.testBit(i) && !i2.testBit(i)) == res.testBit(i));
      }
      // asymmetrical
      i1 = element[1];
      i2 = element[0];
      res = i1.andNot(i2);
      for (int i = 0; i < len; i++) {
        assertTrue("andNot reversed", (i1.testBit(i) && !i2.testBit(i)) == res.testBit(i));
      }
    }

    // regression for HARMONY-4653
    try {
      BigInteger.ZERO.andNot(null);
      fail("should throw NPE");
    } catch (Exception e) {
      // expected
    }
    BigInteger bi = new BigInteger(0, new byte[] {});
    assertEquals(BigInteger.ZERO, bi.andNot(BigInteger.ZERO));
  }
Example #6
0
 protected BigInteger modReduce(BigInteger x) {
   if (r != null) {
     boolean negative = x.signum() < 0;
     if (negative) {
       x = x.abs();
     }
     int qLen = q.bitLength();
     boolean rIsOne = r.equals(ECConstants.ONE);
     while (x.bitLength() > (qLen + 1)) {
       BigInteger u = x.shiftRight(qLen);
       BigInteger v = x.subtract(u.shiftLeft(qLen));
       if (!rIsOne) {
         u = u.multiply(r);
       }
       x = u.add(v);
     }
     while (x.compareTo(q) >= 0) {
       x = x.subtract(q);
     }
     if (negative && x.signum() != 0) {
       x = q.subtract(x);
     }
   } else {
     x = x.mod(q);
   }
   return x;
 }
Example #7
0
  private static BigInteger getNearby(BigInteger significand, int binExp, int offset) {
    int nExtraBits = 1;
    int nDec = (int) Math.round(3.0 + (64 + nExtraBits) * Math.log10(2.0));
    BigInteger newFrac = significand.shiftLeft(nExtraBits).add(BigInteger.valueOf(offset));

    int gg = 64 + nExtraBits - binExp - 1;

    BigDecimal bd = new BigDecimal(newFrac);
    if (gg > 0) {
      bd = bd.divide(new BigDecimal(BigInteger.ONE.shiftLeft(gg)));
    } else {
      BigInteger frac = newFrac;
      while (frac.bitLength() + binExp < 180) {
        frac = frac.multiply(BigInteger.TEN);
      }
      int binaryExp = binExp - newFrac.bitLength() + frac.bitLength();

      bd = new BigDecimal(frac.shiftRight(frac.bitLength() - binaryExp - 1));
    }
    int excessPrecision = bd.precision() - nDec;
    if (excessPrecision > 0) {
      bd = bd.setScale(bd.scale() - excessPrecision, BigDecimal.ROUND_HALF_UP);
    }
    return bd.unscaledValue();
  }
 /**
  * Taken a simple approach as given in http://stackoverflow.com/questions/2290057
  * /how-to-generate-a-random-biginteger-value-in-java
  */
 protected BigInteger nextRandomBigInteger(BigInteger n) {
   Random rand = new Random();
   BigInteger result = new BigInteger(n.bitLength(), rand);
   while (result.compareTo(n) >= 0) {
     result = new BigInteger(n.bitLength(), rand);
   }
   return result;
 }
Example #9
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);
  }
Example #10
0
 /**
  * By default BigInteger.toByteArray() returns bytes including a sign bit, since our numbers are
  * always positive this bit is always zero so not too much of a problem. However if the number is
  * an exact multiple of 8 bits then the addition of a sign bit will cause an extra byte to be
  * added to the resulting array. This will cause problems so in this case we strip the first byte
  * off the array before returning.
  */
 private byte[] getBytes(BigInteger big) {
   byte[] bigBytes = big.toByteArray();
   if ((big.bitLength() % 8) != 0) {
     return bigBytes;
   }
   byte[] smallerBytes = new byte[big.bitLength() / 8];
   System.arraycopy(bigBytes, 1, smallerBytes, 0, smallerBytes.length);
   return smallerBytes;
 }
Example #11
0
 /**
  * Gets the fraction as a <tt>float</tt>. This calculates the fraction as the numerator divided by
  * denominator.
  *
  * @return the fraction as a <tt>float</tt>.
  * @see java.lang.Number#floatValue()
  */
 @Override
 public float floatValue() {
   float result = numerator.floatValue() / denominator.floatValue();
   if (Double.isNaN(result)) {
     // Numerator and/or denominator must be out of range:
     // Calculate how far to shift them to put them in range.
     int shift = Math.max(numerator.bitLength(), denominator.bitLength()) - Float.MAX_EXPONENT;
     result =
         numerator.shiftRight(shift).floatValue() / denominator.shiftRight(shift).floatValue();
   }
   return result;
 }
Example #12
0
 @Test
 public void testDivide() {
   BigInteger dividend = BigInteger.valueOf(4566746).pow(4);
   BigInteger divisor = dividend.shiftRight(7).subtract(BigInteger.valueOf(245));
   System.out.println(
       dividend
           + " / "
           + divisor
           + " = "
           + dividend.divide(divisor)
           + " rem "
           + dividend.remainder(divisor));
   System.out.println(
       "N "
           + dividend.bitLength()
           + " - D "
           + divisor.bitLength()
           + " = "
           + (dividend.bitLength() - divisor.bitLength()));
   System.out.println("Q => " + dividend.divide(divisor).bitLength());
   System.out.println("R => " + dividend.remainder(divisor).bitLength());
   System.out.println("----");
   int diff = dividend.bitLength() - divisor.bitLength();
   BigInteger n = dividend.shiftRight(divisor.bitLength());
   BigInteger d = divisor.shiftRight(divisor.bitLength() - 1);
   System.out.println(n + " / " + d + " = " + n.divide(d));
 }
  public SecT113FieldElement(BigInteger x) {
    if (x == null || x.signum() < 0 || x.bitLength() > 113) {
      throw new IllegalArgumentException("x value invalid for SecT113FieldElement");
    }

    this.x = SecT113Field.fromBigInteger(x);
  }
Example #14
0
  @Test
  public void testCheckFunctions() {
    assertFalse(ArbitraryInteger.ZERO.isNegativ());
    assertTrue(ArbitraryInteger.ZERO.isZero());
    assertFalse(ArbitraryInteger.ZERO.isPositiv());
    assertEquals(0, ArbitraryInteger.ZERO.signum());

    assertFalse(ArbitraryInteger.ONE.isNegativ());
    assertFalse(ArbitraryInteger.ONE.isZero());
    assertTrue(ArbitraryInteger.ONE.isPositiv());
    assertEquals(1, ArbitraryInteger.ONE.signum());

    assertTrue(ArbitraryInteger.MINUS_ONE.isNegativ());
    assertFalse(ArbitraryInteger.MINUS_ONE.isZero());
    assertFalse(ArbitraryInteger.MINUS_ONE.isPositiv());
    assertEquals(-1, ArbitraryInteger.MINUS_ONE.signum());

    for (int i = 0; i < this.iterations; i++) {
      BigInteger reference =
          BigInteger.valueOf(this.randomizer.nextLong() - Long.MAX_VALUE)
              .pow(this.randomizer.nextInt(20) + 10);
      ArbitraryInteger proband = ArbitraryInteger.valueOf(reference.toByteArray());
      assertEquals(reference.signum(), proband.signum());
      assertTrue(
          reference.signum() < 0 && proband.isNegativ()
              || reference.signum() > 0 && !proband.isNegativ());
      assertTrue(
          reference.signum() > 0 && proband.isPositiv()
              || reference.signum() < 0 && !proband.isPositiv());
      assertTrue(reference.bitLength() == proband.bitLength());
    }
  }
Example #15
0
  static byte[] buildDH(DHPublicKey key) {
    DataByteOutputStream out = new DataByteOutputStream();
    BigInteger p = key.getParams().getP();
    BigInteger g = key.getParams().getG();
    BigInteger y = key.getY();

    int pLength, gLength, yLength;
    if (g.equals(TWO) && (p.equals(DHPRIME768) || p.equals(DHPRIME1024))) {
      pLength = 1;
      gLength = 0;
    } else {
      pLength = BigIntegerLength(p);
      gLength = BigIntegerLength(g);
    }
    yLength = BigIntegerLength(y);

    out.writeShort(pLength);
    if (pLength == 1) {
      if (p.bitLength() == 768) out.writeByte((byte) 1);
      else out.writeByte((byte) 2);
    } else out.writeBigInteger(p);
    out.writeShort(gLength);
    if (gLength > 0) out.writeBigInteger(g);
    out.writeShort(yLength);
    out.writeBigInteger(y);

    return out.toByteArray();
  }
Example #16
0
 @Test(timeout = 5000L)
 public void powExactLongIntExact() {
   for (long base : LONGS) {
     for (int power : INTS) {
       if (power < 0) continue;
       boolean overflow =
           BigInteger.valueOf(63 - Long.numberOfLeadingZeros(Math.abs(base)))
                   .multiply(BigInteger.valueOf(power))
                   .compareTo(BigInteger.valueOf(64))
               > 0;
       BigInteger expected = overflow ? null : BigInteger.valueOf(base).pow(power);
       if (expected != null && expected.bitLength() <= 63) {
         long value = powExact(base, power);
         assertEquals(base + " ^ " + power, expected.longValue(), value);
         if (value < 10000000000000000L)
           assertEquals(
               base + " ^ " + power, power == 1 ? base : (long) Math.pow(base, power), value);
         assertEquals(base + " ^ " + power, pow(base, power), value);
       } else {
         try {
           powExact(base, power);
           fail("Should overflow: " + base + " ^ " + power);
         } catch (ArithmeticException e) {
         }
       }
     }
   }
 }
Example #17
0
  /**
   * Check the length of an RSA key modulus/exponent to make sure it is not too short or long. Some
   * impls have their own min and max key sizes that may or may not match with a system defined
   * value.
   *
   * @param modulusLen the bit length of the RSA modulus.
   * @param exponent the RSA exponent
   * @param minModulusLen if > 0, check to see if modulusLen is at least this long, otherwise
   *     unused.
   * @param maxModulusLen caller will allow this max number of bits. Allow the smaller of the
   *     system-defined maximum and this param.
   * @throws InvalidKeyException if any of the values are unacceptable.
   */
  public static void checkKeyLengths(
      int modulusLen, BigInteger exponent, int minModulusLen, int maxModulusLen)
      throws InvalidKeyException {

    if ((minModulusLen > 0) && (modulusLen < (minModulusLen))) {
      throw new InvalidKeyException("RSA keys must be at least " + minModulusLen + " bits long");
    }

    // Even though our policy file may allow this, we don't want
    // either value (mod/exp) to be too big.

    int maxLen = Math.min(maxModulusLen, MAX_MODLEN);

    // If a RSAPrivateKey/RSAPublicKey, make sure the
    // modulus len isn't too big.
    if (modulusLen > maxLen) {
      throw new InvalidKeyException("RSA keys must be no longer than " + maxLen + " bits");
    }

    // If a RSAPublicKey, make sure the exponent isn't too big.
    if (restrictExpLen
        && (exponent != null)
        && (modulusLen > MAX_MODLEN_RESTRICT_EXP)
        && (exponent.bitLength() > MAX_RESTRICTED_EXPLEN)) {
      throw new InvalidKeyException(
          "RSA exponents can be no longer than "
              + MAX_RESTRICTED_EXPLEN
              + " bits "
              + " if modulus is greater than "
              + MAX_MODLEN_RESTRICT_EXP
              + " bits");
    }
  }
Example #18
0
 public static long toLong(String values) throws NumberFormatException {
   // Long.parseLong() can't handle HexStrings with MSB set. Sigh.
   BigInteger bi = new BigInteger(values.replaceAll(":", ""), 16);
   if (bi.bitLength() > 64)
     throw new NumberFormatException("Input string too big to fit in long: " + values);
   return bi.longValue();
 }
 @Override
 public ByteBuffer write(ByteBuffer buff, Object obj) {
   if (!isBigInteger(obj)) {
     return super.write(buff, obj);
   }
   BigInteger x = (BigInteger) obj;
   if (BigInteger.ZERO.equals(x)) {
     buff.put((byte) TAG_BIG_INTEGER_0);
   } else if (BigInteger.ONE.equals(x)) {
     buff.put((byte) TAG_BIG_INTEGER_1);
   } else {
     int bits = x.bitLength();
     if (bits <= 63) {
       buff.put((byte) TAG_BIG_INTEGER_SMALL);
       DataUtils.writeVarLong(buff, x.longValue());
     } else {
       buff.put((byte) TYPE_BIG_INTEGER);
       byte[] bytes = x.toByteArray();
       DataUtils.writeVarInt(buff, bytes.length);
       buff = DataUtils.ensureCapacity(buff, bytes.length);
       buff.put(bytes);
     }
   }
   return buff;
 }
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.println("enter a num");
    int num = in.nextInt();

    for (int x = 1; x <= num; x++) {
      System.out.println("loop enter");
      Scanner in1 = new Scanner(System.in);
      BigInteger number = new BigInteger(in1.nextLine());
      // number=in.nextLine();
      int bitLength = number.bitLength();

      if (bitLength <= Short.SIZE) {
        System.out.println(number + " can be fitted in:");
        System.out.println("* short");
        if (bitLength <= Integer.SIZE) System.out.println("* int");
        if (bitLength <= Long.SIZE) System.out.println("* long");
      } else if (bitLength <= Integer.SIZE) {
        System.out.println(number + " can be fitted in:");
        System.out.println("* int");
        if (bitLength <= Long.SIZE) System.out.println("* long");
      } else if (bitLength <= Long.SIZE) {
        System.out.println(number + " can be fitted in:");
        System.out.println("* long");
      }

      if (bitLength > Long.SIZE) System.out.println(number + " can't be fitted anywhere.");
    }
  }
Example #21
0
  /**
   * Convert decimal to hexadecimal�iNo limit string length�j <br>
   * Return hexadecimal string (unsigned integer number string) from decimal(integer number) <br>
   * In case parameter is a minus number, return blank string <br>
   *
   * @param argStr decimal string
   * @return hexadecimal string
   */
  public static String chgHexString(String argStr) {

    // In case parameter is a minus number, return blank string
    if (argStr.charAt(0) == '-') {
      return "";
    }

    StringBuffer hexb = new StringBuffer();
    BigInteger bi = new BigInteger(argStr);
    int tempInt;
    BigInteger tempBi;

    // Convert each 4 bit, start from the end.
    for (int bitlength = bi.bitLength(); bitlength > 0; bitlength -= 4) {
      tempBi = bi.and(HEX_MASK);
      tempInt = tempBi.intValue();
      hexb.append(HEX_STR.charAt(tempInt));
      bi = bi.shiftRight(4);
    }
    // correction after converting
    int hexlength = hexb.length();
    if (hexlength == 0) {
      // In case value =0, put "00"
      hexb.append("00");
    } else if ((hexlength % 2) == 1) {
      // After converting, if result is a old number string, add "0" at
      // the end of string
      hexb.append("0");
    }

    // Reverse result string (because string was converted from the
    // 4-bit-end)
    return hexb.reverse().toString();
  }
Example #22
0
 public static void main(String args[]) throws Exception {
   Scanner cin = new Scanner(System.in);
   BigInteger s, M;
   int p, i;
   while (cin.hasNext()) {
     p = cin.nextInt();
     s = BigInteger.valueOf(4);
     M = BigInteger.ONE;
     M = M.shiftLeft(p).subtract(BigInteger.ONE);
     for (i = 0; i < p - 2; ++i) {
       s = s.multiply(s).subtract(BigInteger.valueOf(2));
       while (s.bitLength() > p) {
         s = s.shiftRight(p).add(s.and(M));
       }
     }
     if (s.compareTo(BigInteger.ZERO) == 0 || s.compareTo(M) == 0) {
       System.out.println(0);
       continue;
     }
     String ans = "";
     while (s.compareTo(BigInteger.ZERO) > 0) {
       long buf = s.mod(BigInteger.valueOf(16)).longValue();
       ans += Integer.toHexString((int) buf);
       s = s.divide(BigInteger.valueOf(16));
     }
     for (i = ans.length() - 1; i >= 0; --i) System.out.print(ans.charAt(i));
     System.out.println();
   }
 }
Example #23
0
  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};
  }
Example #24
0
 @Override
 public void write(WriteBuffer buff, Object obj) {
   if (!isBigDecimal(obj)) {
     super.write(buff, obj);
     return;
   }
   BigDecimal x = (BigDecimal) obj;
   if (BigDecimal.ZERO.equals(x)) {
     buff.put((byte) TAG_BIG_DECIMAL_0);
   } else if (BigDecimal.ONE.equals(x)) {
     buff.put((byte) TAG_BIG_DECIMAL_1);
   } else {
     int scale = x.scale();
     BigInteger b = x.unscaledValue();
     int bits = b.bitLength();
     if (bits < 64) {
       if (scale == 0) {
         buff.put((byte) TAG_BIG_DECIMAL_SMALL);
       } else {
         buff.put((byte) TAG_BIG_DECIMAL_SMALL_SCALED).putVarInt(scale);
       }
       buff.putVarLong(b.longValue());
     } else {
       byte[] bytes = b.toByteArray();
       buff.put((byte) TYPE_BIG_DECIMAL).putVarInt(scale).putVarInt(bytes.length).put(bytes);
     }
   }
 }
Example #25
0
 @Test(timeout = 5000L)
 public void powExactIntIntExact() {
   for (int base : INTS) {
     for (int power : INTS) {
       if (power < 0) continue;
       boolean overflow =
           BigInteger.valueOf(31 - Integer.numberOfLeadingZeros(Math.abs(base)))
                   .multiply(BigInteger.valueOf(power))
                   .compareTo(BigInteger.valueOf(32))
               > 0;
       BigInteger expected = overflow ? null : BigInteger.valueOf(base).pow(power);
       if (expected != null && expected.bitLength() <= 31) {
         int value = powExact(base, power);
         assertEquals(base + " ^ " + power, expected.intValue(), value);
         assertEquals(base + " ^ " + power, (int) Math.pow(base, power), value);
         assertEquals(base + " ^ " + power, pow(base, power), value);
       } else {
         try {
           powExact(base, power);
           fail("Should overflow: " + base + " ^ " + power);
         } catch (ArithmeticException e) {
         }
       }
     }
   }
 }
 /** @tests java.math.BigInteger#xor(java.math.BigInteger) */
 @TestTargetNew(
     level = TestLevel.COMPLETE,
     notes = "",
     method = "xor",
     args = {java.math.BigInteger.class})
 public void test_xorLjava_math_BigInteger() {
   for (BigInteger[] element : booleanPairs) {
     BigInteger i1 = element[0], i2 = element[1];
     BigInteger res = i1.xor(i2);
     assertTrue("symmetry of xor", res.equals(i2.xor(i1)));
     int len = Math.max(i1.bitLength(), i2.bitLength()) + 66;
     for (int i = 0; i < len; i++) {
       assertTrue("xor", (i1.testBit(i) ^ i2.testBit(i)) == res.testBit(i));
     }
   }
 }
 @Override
 public ByteBuffer write(ByteBuffer buff, Object obj) {
   if (!isBigDecimal(obj)) {
     return super.write(buff, obj);
   }
   BigDecimal x = (BigDecimal) obj;
   if (BigDecimal.ZERO.equals(x)) {
     buff.put((byte) TAG_BIG_DECIMAL_0);
   } else if (BigDecimal.ONE.equals(x)) {
     buff.put((byte) TAG_BIG_DECIMAL_1);
   } else {
     int scale = x.scale();
     BigInteger b = x.unscaledValue();
     int bits = b.bitLength();
     if (bits < 64) {
       if (scale == 0) {
         buff.put((byte) TAG_BIG_DECIMAL_SMALL);
       } else {
         buff.put((byte) TAG_BIG_DECIMAL_SMALL_SCALED);
         DataUtils.writeVarInt(buff, scale);
       }
       DataUtils.writeVarLong(buff, b.longValue());
     } else {
       buff.put((byte) TYPE_BIG_DECIMAL);
       DataUtils.writeVarInt(buff, scale);
       byte[] bytes = b.toByteArray();
       DataUtils.writeVarInt(buff, bytes.length);
       buff = DataUtils.ensureCapacity(buff, bytes.length);
       buff.put(bytes);
     }
   }
   return buff;
 }
Example #28
0
  public void szyfrujPlik(BigInteger e, BigInteger n, String sciezkaDoPlikuOdczyt) {
    String sciezkaPlikZapis =
        "resource\\zaszyfrowany"
            + sciezkaDoPlikuOdczyt.substring(sciezkaDoPlikuOdczyt.indexOf('.'));
    PlikiOdczytZapis plikiOdczytZapis =
        new PlikiOdczytZapis(sciezkaDoPlikuOdczyt, sciezkaPlikZapis, false);

    byte[] zPliku = plikiOdczytZapis.odczyt((int) new File(sciezkaDoPlikuOdczyt).length());

    int liczbaZnakow = n.bitLength() / 8;
    byte[] pomoc = new byte[liczbaZnakow];
    byte[] wynik;
    int j = 0;

    for (int i = 0; i < zPliku.length; i++) {
      if (j < liczbaZnakow) {
        pomoc[j] = zPliku[i];
        j++;
      } else {
        j = 0;
        i--;
        wynik = (szyfrujRSA(new BigInteger(pomoc), e, n).toString() + ' ').getBytes();
        plikiOdczytZapis.zapis(wynik);
        if (zPliku.length - i > liczbaZnakow) {
          pomoc = new byte[liczbaZnakow];
        } else {
          pomoc = new byte[zPliku.length % liczbaZnakow];
        }
      }
    }
    wynik = (szyfrujRSA(new BigInteger(pomoc), e, n).toString()).getBytes();
    plikiOdczytZapis.zapis(wynik);
  }
Example #29
0
  private static void checkNormaliseBaseTenResult(ExpandedDouble orig, NormalisedDecimal result) {
    String sigDigs = result.getSignificantDecimalDigits();
    BigInteger frac = orig.getSignificand();
    while (frac.bitLength() + orig.getBinaryExponent() < 200) {
      frac = frac.multiply(BIG_POW_10);
    }
    int binaryExp = orig.getBinaryExponent() - orig.getSignificand().bitLength();

    String origDigs = frac.shiftLeft(binaryExp + 1).toString(10);

    if (!origDigs.startsWith(sigDigs)) {
      throw new AssertionFailedError("Expected '" + origDigs + "' but got '" + sigDigs + "'.");
    }

    double dO = Double.parseDouble("0." + origDigs.substring(sigDigs.length()));
    double d1 = Double.parseDouble(result.getFractionalPart().toPlainString());
    BigInteger subDigsO = BigInteger.valueOf((int) (dO * 32768 + 0.5));
    BigInteger subDigsB = BigInteger.valueOf((int) (d1 * 32768 + 0.5));

    if (subDigsO.equals(subDigsB)) {
      return;
    }
    BigInteger diff = subDigsB.subtract(subDigsO).abs();
    if (diff.intValue() > 100) {
      // 100/32768 ~= 0.003
      throw new AssertionFailedError("minor mistake");
    }
  }
Example #30
0
  private byte[] bigIntToBytes(BigInteger r) {
    //
    // RFC 2631 (2.1.2) specifies that the secret should be padded with leading zeros if necessary
    // must be the same length as p
    //
    int expectedLength = (p.bitLength() + 7) / 8;

    byte[] tmp = r.toByteArray();

    if (tmp.length == expectedLength) {
      return tmp;
    }

    if (tmp[0] == 0 && tmp.length == expectedLength + 1) {
      byte[] rv = new byte[tmp.length - 1];

      System.arraycopy(tmp, 1, rv, 0, rv.length);
      return rv;
    }

    // tmp must be shorter than expectedLength
    // pad to the left with zeros.
    byte[] rv = new byte[expectedLength];

    System.arraycopy(tmp, 0, rv, rv.length - tmp.length, tmp.length);

    return rv;
  }