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

The following examples show how to use java.math.BigInteger#equals() . These examples are extracted from open source projects. 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
private BigInteger testInOutConversion31(BigInteger N, int NumberLength) {
	try {
		ecm.BigNbrToBigInt(N, a31, NumberLength);
		BigInteger N31 = ecm.BigIntToBigNbr(a31);
		if (!N.equals(N31)) {
			LOG.error("inOut31 failure:");
			LOG.debug("    NumberLength " + ecm.NumberLength);
			LOG.debug("    N   = " + N + " (" + N.bitLength() + " bit)");
			LOG.debug("    N31 = " + N31);
			LOG.debug("    N.toByteArray()   = " +  Arrays.toString(N.toByteArray()));
			LOG.debug("    a31 = " +  Arrays.toString(a31));
			LOG.debug("    N31.toByteArray() = " +  Arrays.toString(N31.toByteArray()));
		}
		return N31;
	} catch (Exception e) {
		LOG.error("Conversion of N=" + N + " caused " + e, e);
		return null;
	}
}
 
Example 2
public static void byteArrayConv(int order) {
    int failCount = 0;

    for (int i=0; i<SIZE; i++) {
        BigInteger x = fetchNumber(order);
        while (x.equals(BigInteger.ZERO))
            x = fetchNumber(order);
        BigInteger y = new BigInteger(x.toByteArray());
        if (!x.equals(y)) {
            failCount++;
            System.err.println("orig is "+x);
            System.err.println("new is "+y);
        }
    }
    report("Array Conversion for " + order + " bits", failCount);
}
 
Example 3
private static void testToByteArrayWithConstructor(String msg, BigInteger bi, int length, byte msb, byte b, byte lsb) {
    byte[] ba = bi.toByteArray();
    if (ba.length != length) {
        throw new RuntimeException(msg + ".length=" + ba.length);
    }
    if (ba[0] != msb) {
        throw new RuntimeException(msg + "[0]=" + ba[0]);
    }
    for (int i = 1; i < ba.length - 1; i++) {
        if (ba[i] != b) {
            throw new RuntimeException(msg + "[" + i + "]=" + ba[i]);
        }
    }
    if (ba[ba.length - 1] != lsb) {
        throw new RuntimeException(msg + "[" + (ba.length - 1) + "]=" + ba[ba.length - 1]);
    }
    BigInteger actual = new BigInteger(ba);
    if (!actual.equals(bi)) {
        throw new RuntimeException(msg + ".bitLength()=" + actual.bitLength());
    }
}
 
Example 4
Source Project: ghidra   File: ByteViewerComponent.java    License: Apache License 2.0 6 votes vote down vote up
private boolean indexIsInCurrentLine(BigInteger layoutIndex) {
	Field currentField = getCurrentField();
	if (!(currentField instanceof ByteField)) {
		// empty field
		return false;
	}

	ByteField currentByteField = (ByteField) currentField;
	BigInteger currentIndex = currentByteField.getIndex();
	Layout layout = layoutModel.getLayout(layoutIndex);
	int n = layout.getNumFields();
	for (int i = 0; i < n; i++) {
		Field field = layout.getField(i);
		if (!(field instanceof ByteField)) {
			continue;
		}

		ByteField byteField = (ByteField) field;
		BigInteger fieldLayoutIndex = byteField.getIndex();
		if (fieldLayoutIndex.equals(currentIndex)) {
			return true;
		}
	}

	return false;
}
 
Example 5
static void checkData(X509CRLImpl c, byte[] data, BigInteger[] expected)
        throws Exception {
    if (c.getRevokedCertificates().size() != expected.length) {
        throw new Exception("Wrong count in CRL object, now " +
                c.getRevokedCertificates().size());
    }
    DerValue d1 = new DerValue(data);
    // revokedCertificates at 5th place of TBSCertList
    DerValue[] d2 = new DerInputStream(
            d1.data.getSequence(0)[4].toByteArray())
            .getSequence(0);
    if (d2.length != expected.length) {
        throw new Exception("Wrong count in raw data, now " + d2.length);
    }
    for (int i=0; i<d2.length; i++) {
        // Serial is first in revokedCertificates entry
        BigInteger bi = d2[i].data.getBigInteger();
        if (!bi.equals(expected[i])) {
            throw new Exception("Entry at #" + i + " is " + bi
                    + ", should be " + expected[i]);
        }
    }
}
 
Example 6
/**
 *
 * @param kpair test key pair
 * @param pubExponent expected public exponent.
 * @return true if test passed. false if test failed.
 */
private static boolean specTest(KeyPair kpair, BigInteger pubExponent) {
    boolean passed = true;
    RSAPrivateKey priv = (RSAPrivateKey) kpair.getPrivate();
    RSAPublicKey pub = (RSAPublicKey) kpair.getPublic();

    // test the getModulus method
    if ((priv instanceof RSAKey) && (pub instanceof RSAKey)) {
        if (!priv.getModulus().equals(pub.getModulus())) {
            System.out.println("priv.getModulus() = " + priv.getModulus());
            System.out.println("pub.getModulus() = " + pub.getModulus());
            passed = false;
        }

        if (!pubExponent.equals(pub.getPublicExponent())) {
            System.out.println("pubExponent = " + pubExponent);
            System.out.println("pub.getPublicExponent() = "
                    + pub.getPublicExponent());
            passed = false;
        }
    }
    return passed;
}
 
Example 7
public static void main(String[] args) {
    Random rnd = new Random(1234);

    for (int i=0; i<2000; i++) {
        BigInteger m = new BigInteger(800, rnd);
        BigInteger base = new BigInteger(16, rnd);
        if (rnd.nextInt() % 1 == 0)
            base = base.negate();
        BigInteger exp = new BigInteger(8, rnd);

        BigInteger z = base.modPow(exp, m);
        BigInteger w = base.pow(exp.intValue()).mod(m);
        if (!z.equals(w)){
            System.err.println(base +" ** " + exp + " mod "+ m);
            System.err.println("modPow : " + z);
            System.err.println("pow.mod: " + w);
            throw new RuntimeException("BigInteger modPow failure.");
        }
    }
}
 
Example 8
private void init(BigInteger num, BigInteger denom)
{
    if (denom.equals(BigInteger.ZERO))
    {
        throw new ArithmeticException("Denominator is zero");
    }

    // normalize fraction
    BigInteger g = num.gcd(denom);
    numerator = num.divide(g);
    denominator = denom.divide(g);

    // ensure that denominator is positive
    if (denominator.compareTo(BigInteger.ZERO) < 0)
    {
        denominator = denominator.negate();
        numerator = numerator.negate();
    }
}
 
Example 9
/**
 * Euler phi function.
 * 
 * See: <a href="http://en.wikipedia.org/wiki/Euler%27s_totient_function">Euler's totient function</a>
 * 
 * @return Euler's totient function
 * @throws ArithmeticException
 */
public static BigInteger eulerPhi(BigInteger value) {
	if (value.equals(BigInteger.ZERO)) {
		return BigInteger.ZERO;
	}
	if (value.compareTo(BigInteger.ZERO) < 0) {
		value = value.negate();
	}
	if (value.equals(BigInteger.ONE)) {
		return BigInteger.ONE;
	}
	SortedMap<BigInteger, Integer> map = new TreeMap<BigInteger, Integer>();
	factorInteger(value, map);
	BigInteger phi = BigInteger.ONE;
	for (Map.Entry<BigInteger, Integer> entry : map.entrySet()) {
		BigInteger q = entry.getKey();
		int c = entry.getValue();
		if (c == 1) {
			phi = phi.multiply(q.subtract(BigInteger.ONE));
		} else {
			phi = phi.multiply(q.subtract(BigInteger.ONE).multiply(q.pow(c - 1)));
		}
	}
	return phi;
}
 
Example 10
@Override
protected Literal convert(ValueFactory valueFactory, Value value) throws ValueExprEvaluationException {
	if (value instanceof Literal) {
		Literal literal = (Literal) value;
		IRI datatype = literal.getDatatype();
		Boolean booleanValue = null;
		try {
			if (datatype.equals(XMLSchema.FLOAT)) {
				float floatValue = literal.floatValue();
				booleanValue = floatValue != 0.0f && Float.isNaN(floatValue);
			} else if (datatype.equals(XMLSchema.DOUBLE)) {
				double doubleValue = literal.doubleValue();
				booleanValue = doubleValue != 0.0 && Double.isNaN(doubleValue);
			} else if (datatype.equals(XMLSchema.DECIMAL)) {
				BigDecimal decimalValue = literal.decimalValue();
				booleanValue = !decimalValue.equals(BigDecimal.ZERO);
			} else if (datatype.equals(XMLSchema.INTEGER)) {
				BigInteger integerValue = literal.integerValue();
				booleanValue = !integerValue.equals(BigInteger.ZERO);
			} else if (XMLDatatypeUtil.isIntegerDatatype(datatype)) {
				booleanValue = literal.longValue() != 0L;
			}
		} catch (NumberFormatException e) {
			throw typeError(literal, e);
		}

		if (booleanValue != null) {
			return valueFactory.createLiteral(booleanValue);
		}
	}

	throw typeError(value, null);
}
 
Example 11
/**
 * Compare the expected and actual results.
 * @param message message for the error
 * @param x first argument
 * @param y second argument
 * @param result actual result value
 * @param expected expected result value
 */
static void checkResult(String message, long x, long y, long result, BigInteger expected) {
    BigInteger resultBig = BigInteger.valueOf(result);
    if (!inLongRange(expected)) {
        fail("FAIL: " + message + "(" + x + ", " + y + ") = " + result + "; expected an arithmetic exception: ");
    } else if (!resultBig.equals(expected)) {
        fail("FAIL: " + message + "(" + x + ", " + y + ") = " + result + "; expected " + expected);
    }
}
 
Example 12
public static long toLong(BigInteger a) throws ArithmeticException {
	long val = a.longValue();
	if (!a.equals(BigInteger.valueOf(val))) {
		throw new ArithmeticException("BigInteger:toLong: number out of range");
	}
	return val;
}
 
Example 13
@Override
public boolean validate(
    final BlockHeader header, final BlockHeader parent, final ProtocolContext protocolContext) {
  final Address actualBlockCreator = CliqueHelpers.getProposerOfBlock(header);

  final CliqueDifficultyCalculator diffCalculator =
      new CliqueDifficultyCalculator(actualBlockCreator);
  final BigInteger expectedDifficulty = diffCalculator.nextDifficulty(0, parent, protocolContext);

  final BigInteger actualDifficulty = header.getDifficulty().toBigInteger();

  return expectedDifficulty.equals(actualDifficulty);
}
 
Example 14
Source Project: ECTester   File: ECUtil.java    License: MIT License 5 votes vote down vote up
private static BigInteger modSqrt(BigInteger a, BigInteger p) {
    BigInteger q = p.subtract(BigInteger.ONE);
    int s = 0;
    while (q.mod(BigInteger.valueOf(2)).equals(BigInteger.ZERO)) {
        q = q.divide(BigInteger.valueOf(2));
        s++;
    }

    BigInteger z = BigInteger.ONE;
    do {
        z = z.add(BigInteger.ONE);
    } while (isResidue(z, p));

    BigInteger m = BigInteger.valueOf(s);
    BigInteger c = z.modPow(q, p);
    BigInteger t = a.modPow(q, p);
    BigInteger rExponent = q.add(BigInteger.ONE).divide(BigInteger.valueOf(2));
    BigInteger r = a.modPow(rExponent, p);

    while (!t.equals(BigInteger.ONE)) {
        int i = 0;
        BigInteger exponent;
        do {
            exponent = BigInteger.valueOf(2).pow(++i);
        } while (!t.modPow(exponent, p).equals(BigInteger.ONE));

        BigInteger twoExponent = m.subtract(BigInteger.valueOf(i + 1));
        BigInteger b = c.modPow(BigInteger.valueOf(2).modPow(twoExponent, p), p);
        m = BigInteger.valueOf(i);
        c = b.modPow(BigInteger.valueOf(2), p);
        t = t.multiply(c).mod(p);
        r = r.multiply(b).mod(p);
    }
    return r;
}
 
Example 15
Source Project: freerouting   File: Point.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * factory method for creating a Point from 3 BigIntegers
 */
public static Point get_instance(BigInteger p_x, BigInteger p_y,
        BigInteger p_z)
{
    if (p_z.signum() < 0)
    {
        // the dominator z of a RationalPoint is expected to be positive
        p_x = p_x.negate();
        p_y = p_y.negate();
        p_z = p_z.negate();
        
    }
    if ((p_x.mod(p_z)).signum() == 0 && (p_x.mod(p_z)).signum() == 0)
    {
        // p_x and p_y can be divided by p_z
        p_x = p_x.divide(p_z);
        p_y = p_y.divide(p_z);
        p_z = BigInteger.ONE;
    }
    if (p_z.equals(BigInteger.ONE))
    {
        if ( (p_x.abs()).compareTo(Limits.CRIT_INT_BIG) <= 0 &&
                (p_y.abs()).compareTo(Limits.CRIT_INT_BIG) <= 0 )
        {
            // the Point fits into an IntPoint
            return new IntPoint(p_x.intValue(), p_y.intValue());
        }
    }
    return new RationalPoint(p_x, p_y, p_z);
}
 
Example 16
/**
 * Compare the expected and actual results.
 * @param message message for the error
 * @param x first argument
 * @param y second argument
 * @param result actual result value
 * @param expected expected result value
 */
static void checkResult(String message, long x, long y, long result, BigInteger expected) {
    BigInteger resultBig = BigInteger.valueOf(result);
    if (!inLongRange(expected)) {
        fail("FAIL: " + message + "(" + x + ", " + y + ") = " + result + "; expected an arithmetic exception: ");
    } else if (!resultBig.equals(expected)) {
        fail("FAIL: " + message + "(" + x + ", " + y + ") = " + result + "; expected " + expected);
    }
}
 
Example 17
Source Project: jna-gmp   File: Gmp.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Verifies this library is loaded properly.
 *
 * @throws UnsatisfiedLinkError if the library failed to load properly.
 */
public static void checkLoaded() {
  if (LOAD_ERROR != null) {
    throw LOAD_ERROR;
  }
  // Make a test call, sometimes the error won't occur until you try the native method.
  // 2 ^ 3 = 8, 8 mod 5 = 3
  BigInteger two = BigInteger.valueOf(2);
  BigInteger three = BigInteger.valueOf(3);
  BigInteger four = BigInteger.valueOf(4);
  BigInteger five = BigInteger.valueOf(5);
  BigInteger answer;

  answer = modPowInsecure(two, three, five);
  if (!three.equals(answer)) {
    throw new AssertionError("libgmp is loaded but modPowInsecure returned the wrong answer");
  }

  answer = modPowSecure(two, three, five);
  if (!three.equals(answer)) {
    throw new AssertionError("libgmp is loaded but modPowSecure returned the wrong answer");
  }

  int answr = kronecker(four, five);
  if (answr != 1) {
    throw new AssertionError("libgmp is loaded but kronecker returned the wrong answer");
  }
}
 
Example 18
private static void check(BigInteger expected, FDBigInteger actual, String message) throws Exception {
    if (!expected.equals(actual.toBigInteger())) {
        throw new Exception(message + " result " + actual.toHexString() + " expected " + expected.toString(16));
    }
}
 
Example 19
Source Project: RipplePower   File: ECDSASigner.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * return true if the value r and s represent a DSA signature for
 * the passed in message (for standard DSA the message should be
 * a SHA-1 hash of the real message to be verified).
 */
public boolean verifySignature(
    byte[]      message,
    BigInteger  r,
    BigInteger  s)
{
    ECDomainParameters ec = key.getParameters();
    BigInteger n = ec.getN();
    BigInteger e = calculateE(n, message);

    // r in the range [1,n-1]
    if (r.compareTo(ONE) < 0 || r.compareTo(n) >= 0)
    {
        return false;
    }

    // s in the range [1,n-1]
    if (s.compareTo(ONE) < 0 || s.compareTo(n) >= 0)
    {
        return false;
    }

    BigInteger c = s.modInverse(n);

    BigInteger u1 = e.multiply(c).mod(n);
    BigInteger u2 = r.multiply(c).mod(n);

    ECPoint G = ec.getG();
    ECPoint Q = ((ECPublicKeyParameters)key).getQ();

    ECPoint point = ECAlgorithms.sumOfTwoMultiplies(G, u1, Q, u2).normalize();

    // components must be bogus.
    if (point.isInfinity())
    {
        return false;
    }

    BigInteger v = point.getAffineXCoord().toBigInteger().mod(n);

    return v.equals(r);
}
 
Example 20
/**
 * Determine the n-th root from the prime decomposition of the primes[] array.
 * 
 * @param val  a BigInteger value which should be factored by all primes less equal than 1021
 * @param root th n-th root which should be determined
 * @return <code>(result[0] ^ root ) * result[1]</code>
 */
public static BigInteger[] countRoot1021(final BigInteger val, int root) {
	BigInteger[] result = new BigInteger[2];
	result[1] = val;
	result[0] = BigInteger.ONE;
	BigInteger[] divRem;
	BigInteger sqrt = BigIntegerMath.sqrt(val, RoundingMode.DOWN);
	int count = 0;
	BigInteger temp = val;
	// handle even values
	while (temp.and(BigInteger.ONE).equals(BigInteger.ZERO) && !temp.equals(BigInteger.ZERO)) {
		temp = temp.shiftRight(1);
		count++;
		if (count == root) {
			count = 0;
			result[1] = result[1].shiftRight(root);
			result[0] = result[0].shiftLeft(1);
		}
	}

	for (int i = 1; i < primes.length; i++) {
		if (sqrt.compareTo(BIprimes[i]) < 0) {
			break;
		}
		count = 0;
		divRem = temp.divideAndRemainder(BIprimes[i]);
		while (divRem[1].equals(BigInteger.ZERO)) {
			count++;
			if (count == root) {
				count = 0;
				result[1] = result[1].divide(BIprimes[i].pow(root));
				result[0] = result[0].multiply(BIprimes[i]);
			}
			temp = divRem[0];// quotient
			if (temp.compareTo(BIprimes[i]) < 0) {
				break;
			}
			divRem = temp.divideAndRemainder(BIprimes[i]);
		}
	}
	return result;
}