Java Code Examples for java.math.BigInteger#signum()

The following examples show how to use java.math.BigInteger#signum() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RationalNumber.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** Simple constructor.
 * Build a rational number from a numerator and a denominator.
 * @param numerator numerator of the rational number
 * @param denominator denominator of the rational number
 * @exception ArithmeticException if the denominator is zero
 */
public RationalNumber(BigInteger numerator, BigInteger denominator) {

  if (denominator.signum() == 0) {
    throw new ArithmeticException("divide by zero");
  }

  p = numerator;
  q = denominator;

  if (q.signum() < 0) {
    p = p.negate();
    q = q.negate();
  }

  simplify();

}
 
Example 2
Source File: SecureBox.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private static void validateEcPoint(BigInteger x, BigInteger y) throws InvalidKeyException {
    if (x.compareTo(EC_PARAM_P) >= 0
            || y.compareTo(EC_PARAM_P) >= 0
            || x.signum() == -1
            || y.signum() == -1) {
        throw new InvalidKeyException("Point lies outside of the expected curve");
    }

    // Points on the curve satisfy y^2 = x^3 + ax + b (mod p)
    BigInteger lhs = y.modPow(BIG_INT_02, EC_PARAM_P);
    BigInteger rhs =
            x.modPow(BIG_INT_02, EC_PARAM_P) // x^2
                    .add(EC_PARAM_A) // x^2 + a
                    .mod(EC_PARAM_P) // This will speed up the next multiplication
                    .multiply(x) // (x^2 + a) * x = x^3 + ax
                    .add(EC_PARAM_B) // x^3 + ax + b
                    .mod(EC_PARAM_P);
    if (!lhs.equals(rhs)) {
        throw new InvalidKeyException("Point lies outside of the expected curve");
    }
}
 
Example 3
Source File: Gmp.java    From jna-gmp with Apache License 2.0 6 votes vote down vote up
private BigInteger modPowSecureImpl(BigInteger base, BigInteger exp, BigInteger mod) {
  boolean invert = exp.signum() < 0;
  if (invert) {
    exp = exp.negate();
  }

  mpz_t basePeer = getPeer(base, sharedOperands[0]);
  mpz_t expPeer = getPeer(exp, sharedOperands[1]);
  mpz_t modPeer = getPeer(mod, sharedOperands[2]);

  if (invert) {
    int res = __gmpz_invert(basePeer, basePeer, modPeer);
    if (res == 0) {
      throw new ArithmeticException("val not invertible");
    }
  }

  __gmpz_powm_sec(sharedOperands[3], basePeer, expPeer, modPeer);

  // The result size should be <= modulus size, but round up to the nearest byte.
  int requiredSize = (mod.bitLength() + 7) / 8;
  return new BigInteger(mpzSgn(sharedOperands[3]), mpzExport(sharedOperands[3], requiredSize));
}
 
Example 4
Source File: NumericType.java    From etherjar with Apache License 2.0 6 votes vote down vote up
@Override
public Hex32 encodeSimple(BigInteger value) {
    if (!isValueValid(value))
        throw new IllegalArgumentException("Numeric value out of range: " + value);

    byte[] data = value.toByteArray();

    byte[] arr = new byte[Hex32.SIZE_BYTES];

    if (value.signum() == -1) {
        System.arraycopy(NEGATIVE_ARRAY_FOR_PADDING, 0, arr, 0, Hex32.SIZE_BYTES);
    }

    int bytes = bits >>> 3;

    if (data.length > bytes) {
        System.arraycopy(data, data.length - bytes, arr, Hex32.SIZE_BYTES - bytes, bytes);
    } else {
        System.arraycopy(data, 0, arr, Hex32.SIZE_BYTES - data.length, data.length);
    }

    return new Hex32(arr);
}
 
Example 5
Source File: ECAlgorithms.java    From RipplePower with Apache License 2.0 6 votes vote down vote up
static ECPoint implShamirsTrickWNaf(ECPoint P, BigInteger k,
    ECPoint Q, BigInteger l)
{
    boolean negK = k.signum() < 0, negL = l.signum() < 0;

    k = k.abs();
    l = l.abs();

    int widthP = Math.max(2, Math.min(16, WNafUtil.getWindowSize(k.bitLength())));
    int widthQ = Math.max(2, Math.min(16, WNafUtil.getWindowSize(l.bitLength())));

    WNafPreCompInfo infoP = WNafUtil.precompute(P, widthP, true);
    WNafPreCompInfo infoQ = WNafUtil.precompute(Q, widthQ, true);

    ECPoint[] preCompP = negK ? infoP.getPreCompNeg() : infoP.getPreComp();
    ECPoint[] preCompQ = negL ? infoQ.getPreCompNeg() : infoQ.getPreComp();
    ECPoint[] preCompNegP = negK ? infoP.getPreComp() : infoP.getPreCompNeg();
    ECPoint[] preCompNegQ = negL ? infoQ.getPreComp() : infoQ.getPreCompNeg();

    byte[] wnafP = WNafUtil.generateWindowNaf(widthP, k);
    byte[] wnafQ = WNafUtil.generateWindowNaf(widthQ, l);

    return implShamirsTrickWNaf(preCompP, preCompNegP, wnafP, preCompQ, preCompNegQ, wnafQ);
}
 
Example 6
Source File: ModInvTime.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static void check(BigInteger val, BigInteger mod, BigInteger inv) {
    BigInteger r = inv.multiply(val).remainder(mod);
    if (r.signum() == -1)
        r = r.add(mod);
    if (!r.equals(BigInteger.ONE))
        throw new RuntimeException("Numerically incorrect modular inverse");
}
 
Example 7
Source File: TestFDBigInteger.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void testMultByPow52(FDBigInteger t, int p5, int p2) throws Exception {
    BigInteger bt = t.toBigInteger();
    FDBigInteger r = t.multByPow52(p5, p2);
    if (bt.signum() == 0 && r != t) {
        throw new Exception("multByPow52 of doesn't reuse its argument");
    }
    check(bt.multiply(biPow52(p5, p2)), r, "multByPow52 returns wrong result");
}
 
Example 8
Source File: TestFDBigInteger.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void testLeftShift(FDBigInteger t, int shift, boolean isImmutable) throws Exception {
    BigInteger bt = t.toBigInteger();
    FDBigInteger r = t.leftShift(shift);
    if ((bt.signum() == 0 || shift == 0 || !isImmutable) && r != t) {
        throw new Exception("leftShift doesn't reuse its argument");
    }
    if (isImmutable) {
        check(bt, t, "leftShift corrupts its argument");
    }
    check(bt.shiftLeft(shift), r, "leftShift returns wrong result");
}
 
Example 9
Source File: Curve25519FieldElement.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
public Curve25519FieldElement(BigInteger x)
{
    if (x == null || x.signum() < 0 || x.compareTo(Q) >= 0)
    {
        throw new IllegalArgumentException("x value invalid for Curve25519FieldElement");
    }

    this.x = Curve25519Field.fromBigInteger(x);
}
 
Example 10
Source File: WNafUtil.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
public static byte[] generateNaf(BigInteger k)
{
    if (k.signum() == 0)
    {
        return EMPTY_BYTES;
    }

    BigInteger _3k = k.shiftLeft(1).add(k);

    int digits = _3k.bitLength() - 1;
    byte[] naf = new byte[digits];

    BigInteger diff = _3k.xor(k);

    for (int i = 1; i < digits; ++i)
    {
        if (diff.testBit(i))
        {
            naf[i - 1] = (byte)(k.testBit(i) ? -1 : 1);
            ++i;
        }
    }

    naf[digits - 1] = 1;

    return naf;
}
 
Example 11
Source File: RSACore.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * RSA private key operations with CRT. Algorithm and variable naming
 * are taken from PKCS#1 v2.1, section 5.1.2.
 *
 * The only difference is the addition of blinding to twart timing attacks.
 * This is described in the RSA Bulletin#2 (Jan 96) among other places.
 * This means instead of implementing RSA as
 *   m = c ^ d mod n (or RSA in CRT variant)
 * we do
 *   r  = random(0, n-1)
 *   c' = c  * r^e  mod n
 *   m' = c' ^ d    mod n (or RSA in CRT variant)
 *   m  = m' * r^-1 mod n (where r^-1 is the modular inverse of r mod n)
 * This works because r^(e*d) * r^-1 = r * r^-1 = 1 (all mod n)
 *
 * We do not generate new blinding parameters for each operation but reuse
 * them BLINDING_MAX_REUSE times (see definition below).
 */
private static byte[] crtCrypt(byte[] msg, RSAPrivateCrtKey key)
        throws BadPaddingException {
    BigInteger n = key.getModulus();
    BigInteger c = parseMsg(msg, n);
    BigInteger p = key.getPrimeP();
    BigInteger q = key.getPrimeQ();
    BigInteger dP = key.getPrimeExponentP();
    BigInteger dQ = key.getPrimeExponentQ();
    BigInteger qInv = key.getCrtCoefficient();

    BlindingParameters params;
    if (ENABLE_BLINDING) {
        params = getBlindingParameters(key);
        c = c.multiply(params.re).mod(n);
    } else {
        params = null;
    }

    // m1 = c ^ dP mod p
    BigInteger m1 = c.modPow(dP, p);
    // m2 = c ^ dQ mod q
    BigInteger m2 = c.modPow(dQ, q);

    // h = (m1 - m2) * qInv mod p
    BigInteger mtmp = m1.subtract(m2);
    if (mtmp.signum() < 0) {
        mtmp = mtmp.add(p);
    }
    BigInteger h = mtmp.multiply(qInv).mod(p);

    // m = m2 + q * h
    BigInteger m = h.multiply(q).add(m2);

    if (params != null) {
        m = m.multiply(params.rInv).mod(n);
    }

    return toByteArray(m, getByteLength(n));
}
 
Example 12
Source File: SuperSerial.java    From headlong with Apache License 2.0 5 votes vote down vote up
private static byte[] toSigned(int typeBits, BigInteger val) {
    final int signum = val.signum();
    if(signum == 0) {
        return Strings.EMPTY_BYTE_ARRAY;
    }
    final byte[] bytes = val.toByteArray();
    return signum < 0
            ? signExtendNegative(bytes, typeBits / Byte.SIZE)
            : bytes[0] != 0
                ? bytes
                : Arrays.copyOfRange(bytes, 1, bytes.length);
}
 
Example 13
Source File: Strings.java    From JavaSteam with MIT License 5 votes vote down vote up
public String asUnsignedDecimalString(long l) {
    BigInteger b = BigInteger.valueOf(l);
    if (b.signum() < 0) {
        b = b.add(TWO_64);
    }
    return b.toString();
}
 
Example 14
Source File: DSAKeyPairGenerator.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Generate the private key component of the key pair using the
 * provided source of random bits. This method uses the random but
 * source passed to generate a seed and then calls the seed-based
 * generateX method.
 */
private BigInteger generateX(SecureRandom random, BigInteger q) {
    BigInteger x = null;
    byte[] temp = new byte[qlen];
    while (true) {
        random.nextBytes(temp);
        x = new BigInteger(1, temp).mod(q);
        if (x.signum() > 0 && (x.compareTo(q) < 0)) {
            return x;
        }
    }
}
 
Example 15
Source File: ObjectIdentifier.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void checkFirstComponent(BigInteger first) throws IOException {
    if (first.signum() == -1 ||
            first.compareTo(BigInteger.valueOf(2)) == 1) {
        throw new IOException("ObjectIdentifier() -- " +
                "First oid component is invalid ");
    }
}
 
Example 16
Source File: CompactNumberFormat.java    From Bytecoder with Apache License 2.0 4 votes vote down vote up
private StringBuffer format(BigInteger number, StringBuffer result,
        FieldDelegate delegate, boolean formatLong) {

    boolean isNegative = number.signum() == -1;
    if (isNegative) {
        number = number.negate();
    }

    int compactDataIndex = selectCompactPattern(number);
    if (compactDataIndex != -1) {
        Number divisor = divisors.get(compactDataIndex);
        int iPart = getIntegerPart(number.doubleValue(), divisor.doubleValue());
        String prefix = getAffix(false, true, isNegative, compactDataIndex, iPart);
        String suffix = getAffix(false, false, isNegative, compactDataIndex, iPart);
        if (!prefix.isEmpty() || !suffix.isEmpty()) {
            appendPrefix(result, prefix, delegate);
            if (number.mod(new BigInteger(divisor.toString()))
                    .compareTo(BigInteger.ZERO) == 0) {
                number = number.divide(new BigInteger(divisor.toString()));

                decimalFormat.setDigitList(number, isNegative, 0);
                decimalFormat.subformatNumber(result, delegate,
                        isNegative, true, getMaximumIntegerDigits(),
                        getMinimumIntegerDigits(), getMaximumFractionDigits(),
                        getMinimumFractionDigits());
            } else {
                // To avoid truncation of fractional part store the value in
                // BigDecimal and follow BigDecimal path instead of
                // BigInteger path
                BigDecimal nDecimal = new BigDecimal(number)
                        .divide(new BigDecimal(divisor.toString()), getRoundingMode());
                decimalFormat.setDigitList(nDecimal, isNegative, getMaximumFractionDigits());
                decimalFormat.subformatNumber(result, delegate,
                        isNegative, false, getMaximumIntegerDigits(),
                        getMinimumIntegerDigits(), getMaximumFractionDigits(),
                        getMinimumFractionDigits());
            }
            appendSuffix(result, suffix, delegate);
        } else {
            number = isNegative ? number.negate() : number;
            defaultDecimalFormat.format(number, result, delegate, formatLong);
        }
    } else {
        number = isNegative ? number.negate() : number;
        defaultDecimalFormat.format(number, result, delegate, formatLong);
    }
    return result;
}
 
Example 17
Source File: NumberUtil.java    From symja_android_library with GNU General Public License v3.0 4 votes vote down vote up
public static BigInteger checkPositive(String role, BigInteger x) {
	if (x.signum() <= 0) {
		throw new IllegalArgumentException(role + " (" + x + ") must be > 0");
	}
	return x;
}
 
Example 18
Source File: ObjectIdentifier.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
private static void checkOtherComponent(int i, BigInteger num) throws IOException {
    if (num.signum() == -1) {
        throw new IOException("ObjectIdentifier() -- " +
                "oid component #" + (i+1) + " must be non-negative ");
    }
}
 
Example 19
Source File: ECFieldFp.java    From jdk1.8-source-analysis with Apache License 2.0 3 votes vote down vote up
/**
 * Creates an elliptic curve prime finite field
 * with the specified prime {@code p}.
 * @param p the prime.
 * @exception NullPointerException if {@code p} is null.
 * @exception IllegalArgumentException if {@code p}
 * is not positive.
 */
public ECFieldFp(BigInteger p) {
    if (p.signum() != 1) {
        throw new IllegalArgumentException("p is not positive");
    }
    this.p = p;
}
 
Example 20
Source File: ECFieldFp.java    From j2objc with Apache License 2.0 3 votes vote down vote up
/**
 * Creates an elliptic curve prime finite field
 * with the specified prime {@code p}.
 * @param p the prime.
 * @exception NullPointerException if {@code p} is null.
 * @exception IllegalArgumentException if {@code p}
 * is not positive.
 */
public ECFieldFp(BigInteger p) {
    if (p.signum() != 1) {
        throw new IllegalArgumentException("p is not positive");
    }
    this.p = p;
}