java.math.BigInteger

Here are the examples of the java api class java.math.BigInteger taken from open source projects.

1. OverloadedNumberUtilTest#testBigIntegerCoercion()

View license
public void testBigIntegerCoercion() {
    BigInteger bi;
    cipEqu(BigInteger.ZERO, new OverloadedNumberUtil.BigIntegerOrByte(BigInteger.ZERO));
    bi = new BigInteger(String.valueOf(Byte.MAX_VALUE));
    cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrByte(bi));
    bi = new BigInteger(String.valueOf(Byte.MIN_VALUE));
    cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrByte(bi));
    bi = new BigInteger(String.valueOf(Byte.MAX_VALUE + 1));
    cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrShort(bi));
    bi = new BigInteger(String.valueOf(Byte.MIN_VALUE - 1));
    cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrShort(bi));
    bi = new BigInteger(String.valueOf(Short.MAX_VALUE));
    cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrShort(bi));
    bi = new BigInteger(String.valueOf(Short.MIN_VALUE));
    cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrShort(bi));
    bi = new BigInteger(String.valueOf(Short.MAX_VALUE + 1));
    cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrInteger(bi));
    bi = new BigInteger(String.valueOf(Short.MIN_VALUE - 1));
    cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrInteger(bi));
    bi = new BigInteger(String.valueOf(Integer.MAX_VALUE));
    cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrInteger(bi));
    bi = new BigInteger(String.valueOf(Integer.MIN_VALUE));
    cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrInteger(bi));
    bi = new BigInteger(String.valueOf(Integer.MAX_VALUE + 1L));
    cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrLong(bi));
    bi = new BigInteger(String.valueOf(Integer.MIN_VALUE - 1L));
    cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrLong(bi));
    bi = new BigInteger(String.valueOf(Long.MAX_VALUE));
    cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrLong(bi));
    bi = new BigInteger(String.valueOf(Long.MIN_VALUE));
    cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrLong(bi));
    cipEqu(new BigInteger(String.valueOf(Long.MAX_VALUE)).add(BigInteger.ONE));
    cipEqu(new BigInteger(String.valueOf(Long.MIN_VALUE)).subtract(BigInteger.ONE));
    bi = new BigInteger("0");
    cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrFloat(bi), TypeFlags.DOUBLE | TypeFlags.FLOAT);
    cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrFloat(bi), TypeFlags.MASK_KNOWN_NONINTEGERS);
    cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrFloat(bi), TypeFlags.FLOAT);
    cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrDouble(bi), TypeFlags.DOUBLE);
    bi = new BigInteger("16777215");
    cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrFloat(bi), TypeFlags.MASK_KNOWN_NONINTEGERS);
    bi = new BigInteger("-16777215");
    cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrFloat(bi), TypeFlags.MASK_KNOWN_NONINTEGERS);
    bi = new BigInteger("16777216");
    cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrFloat(bi), TypeFlags.MASK_KNOWN_NONINTEGERS);
    bi = new BigInteger("-16777216");
    cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrFloat(bi), TypeFlags.MASK_KNOWN_NONINTEGERS);
    bi = new BigInteger("16777217");
    cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrDouble(bi), TypeFlags.MASK_KNOWN_NONINTEGERS);
    cipEqu(bi, TypeFlags.FLOAT);
    bi = new BigInteger("-16777217");
    cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrDouble(bi), TypeFlags.MASK_KNOWN_NONINTEGERS);
    cipEqu(bi, TypeFlags.FLOAT);
    bi = new BigInteger("9007199254740991");
    cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrDouble(bi), TypeFlags.MASK_KNOWN_NONINTEGERS);
    cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrDouble(bi), TypeFlags.DOUBLE);
    bi = new BigInteger("-9007199254740991");
    cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrDouble(bi), TypeFlags.MASK_KNOWN_NONINTEGERS);
    cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrDouble(bi), TypeFlags.DOUBLE);
    bi = new BigInteger("9007199254740992");
    cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrDouble(bi), TypeFlags.MASK_KNOWN_NONINTEGERS);
    cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrDouble(bi), TypeFlags.DOUBLE);
    bi = new BigInteger("-9007199254740992");
    cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrDouble(bi), TypeFlags.MASK_KNOWN_NONINTEGERS);
    cipEqu(bi, new OverloadedNumberUtil.BigIntegerOrDouble(bi), TypeFlags.DOUBLE);
    bi = new BigInteger("9007199254740993");
    cipEqu(bi, TypeFlags.MASK_KNOWN_NONINTEGERS);
    cipEqu(bi, TypeFlags.DOUBLE | TypeFlags.FLOAT);
    cipEqu(bi, TypeFlags.FLOAT);
    cipEqu(bi, TypeFlags.DOUBLE);
    bi = new BigInteger("-9007199254740993");
    cipEqu(bi, TypeFlags.MASK_KNOWN_NONINTEGERS);
    cipEqu(bi, TypeFlags.DOUBLE | TypeFlags.FLOAT);
    cipEqu(bi, TypeFlags.FLOAT);
    cipEqu(bi, TypeFlags.DOUBLE);
    bi = new BigInteger("9007199254740994");
    cipEqu(bi, TypeFlags.MASK_KNOWN_NONINTEGERS);
    bi = new BigInteger("-9007199254740994");
    cipEqu(bi, TypeFlags.MASK_KNOWN_NONINTEGERS);
}

2. SM#proofEqualCoords()

Project: ChatSecureAndroid
Source File: SM.java
View license
/**
     * Proof of knowledge of coordinates with first components being equal
     *
     * @throws SMException
     */
public static BigInteger[] proofEqualCoords(SMState state, BigInteger r, int version) throws SMException {
    BigInteger r1 = randomExponent();
    BigInteger r2 = randomExponent();
    /* Compute the value of c, as c = h(g3^r1, g1^r1 g2^r2) */
    BigInteger temp1 = state.g1.modPow(r1, MODULUS_S);
    BigInteger temp2 = state.g2.modPow(r2, MODULUS_S);
    temp2 = temp1.multiply(temp2).mod(MODULUS_S);
    temp1 = state.g3.modPow(r1, MODULUS_S);
    BigInteger c = hash(version, temp1, temp2);
    /* Compute the d values, as d1 = r1 - r c, d2 = r2 - secret c */
    temp1 = r.multiply(c).mod(ORDER_S);
    BigInteger d1 = r1.subtract(temp1).mod(ORDER_S);
    temp1 = state.secret.multiply(c).mod(ORDER_S);
    BigInteger d2 = r2.subtract(temp1).mod(ORDER_S);
    BigInteger[] ret = new BigInteger[3];
    ret[0] = c;
    ret[1] = d1;
    ret[2] = d2;
    return ret;
}

3. PrivateKeyReader#getRSAKeySpec()

View license
/**
   * Convert PKCS#1 encoded private key into RSAPrivateCrtKeySpec.
   * <p/>
   * <p/>The ASN.1 syntax for the private key with CRT is
   * <p/>
   * <pre>
   * --
   * -- Representation of RSA private key with information for the CRT algorithm.
   * --
   * RSAPrivateKey ::= SEQUENCE {
   *   version           Version,
   *   modulus           INTEGER,  -- n
   *   publicExponent    INTEGER,  -- e
   *   privateExponent   INTEGER,  -- d
   *   prime1            INTEGER,  -- p
   *   prime2            INTEGER,  -- q
   *   exponent1         INTEGER,  -- d mod (p-1)
   *   exponent2         INTEGER,  -- d mod (q-1)
   *   coefficient       INTEGER,  -- (inverse of q) mod p
   *   otherPrimeInfos   OtherPrimeInfos OPTIONAL
   * }
   * </pre>
   *
   * @param keyBytes PKCS#1 encoded key
   * @return KeySpec
   * @throws IOException
   */
private static RSAPrivateCrtKeySpec getRSAKeySpec(byte[] keyBytes) throws IOException {
    DerParser parser = new DerParser(keyBytes);
    Asn1Object sequence = parser.read();
    if (sequence.getType() != DerParser.SEQUENCE) {
        throw new IOException("Invalid DER: not a sequence");
    }
    // Parse inside the sequence
    parser = sequence.getParser();
    // Skip version
    parser.read();
    BigInteger modulus = parser.read().getInteger();
    BigInteger publicExp = parser.read().getInteger();
    BigInteger privateExp = parser.read().getInteger();
    BigInteger prime1 = parser.read().getInteger();
    BigInteger prime2 = parser.read().getInteger();
    BigInteger exp1 = parser.read().getInteger();
    BigInteger exp2 = parser.read().getInteger();
    BigInteger crtCoef = parser.read().getInteger();
    return new RSAPrivateCrtKeySpec(modulus, publicExp, privateExp, prime1, prime2, exp1, exp2, crtCoef);
}

4. DSA#generateV()

Project: jdk7u-jdk
Source File: DSA.java
View license
private BigInteger generateV(BigInteger y, BigInteger p, BigInteger q, BigInteger g, BigInteger w, BigInteger r) throws SignatureException {
    byte[] s2 = getDigest();
    BigInteger temp = new BigInteger(1, s2);
    temp = temp.multiply(w);
    BigInteger u1 = temp.remainder(q);
    BigInteger u2 = (r.multiply(w)).remainder(q);
    BigInteger t1 = g.modPow(u1, p);
    BigInteger t2 = y.modPow(u2, p);
    BigInteger t3 = t1.multiply(t2);
    BigInteger t5 = t3.remainder(p);
    return t5.remainder(q);
}

5. PKCS1EncodedKeySpec#decode()

Project: sakai
Source File: PKCS1EncodedKeySpec.java
View license
/**
     * Decode PKCS#1 encoded private key into RSAPrivateCrtKeySpec.
     * 
     * <p/>The ASN.1 syntax for the private key with CRT is
     * 
     * <pre>
     * -- 
     * -- Representation of RSA private key with information for the CRT algorithm.
     * --
     * RSAPrivateKey ::= SEQUENCE {
     *   version           Version, 
     *   modulus           INTEGER,  -- n
     *   publicExponent    INTEGER,  -- e
     *   privateExponent   INTEGER,  -- d
     *   prime1            INTEGER,  -- p
     *   prime2            INTEGER,  -- q
     *   exponent1         INTEGER,  -- d mod (p-1)
     *   exponent2         INTEGER,  -- d mod (q-1) 
     *   coefficient       INTEGER,  -- (inverse of q) mod p
     *   otherPrimeInfos   OtherPrimeInfos OPTIONAL 
     * }
     * </pre>
     * 
     * @param keyBytes PKCS#1 encoded key
     * @throws IOException
     */
private void decode(byte[] keyBytes) throws IOException {
    DerParser parser = new DerParser(keyBytes);
    Asn1Object sequence = parser.read();
    if (sequence.getType() != DerParser.SEQUENCE)
        //$NON-NLS-1$
        throw new IOException("Invalid DER: not a sequence");
    // Parse inside the sequence
    parser = sequence.getParser();
    // Skip version
    parser.read();
    BigInteger modulus = parser.read().getInteger();
    BigInteger publicExp = parser.read().getInteger();
    BigInteger privateExp = parser.read().getInteger();
    BigInteger prime1 = parser.read().getInteger();
    BigInteger prime2 = parser.read().getInteger();
    BigInteger exp1 = parser.read().getInteger();
    BigInteger exp2 = parser.read().getInteger();
    BigInteger crtCoef = parser.read().getInteger();
    keySpec = new RSAPrivateCrtKeySpec(modulus, publicExp, privateExp, prime1, prime2, exp1, exp2, crtCoef);
}

6. ECComputer#dbl()

Project: TLS-Attacker
Source File: ECComputer.java
View license
/**
     * Doubles point, does not check for infinity
     * 
     * @param p
     * @return
     * @throws DivisionException
     *             exception occurs if y coordinate is zero
     */
public Point dbl(Point p) throws DivisionException {
    BigInteger x = p.getX();
    BigInteger y = p.getY();
    if (y.equals(BigInteger.ZERO)) {
        throw new DivisionException("y was equal to zero");
    }
    BigInteger l1 = ((THREE.multiply(x.pow(2))).add(curve.getA()));
    BigInteger l2 = TWO.multiply(y).modInverse(curve.getP());
    BigInteger l = l1.multiply(l2).mod(curve.getP());
    BigInteger xr = l.pow(2).subtract(TWO.multiply(x)).mod(curve.getP());
    BigInteger yr = l.multiply(x.subtract(xr)).subtract(y).mod(curve.getP());
    Point ret = new Point(xr, yr);
    return ret;
}

7. Tnaf#approximateDivisionByN()

Project: bc-java
Source File: Tnaf.java
View license
/**
     * Approximate division by <code>n</code>. For an integer
     * <code>k</code>, the value <code>λ = s k / n</code> is
     * computed to <code>c</code> bits of accuracy.
     * @param k The parameter <code>k</code>.
     * @param s The curve parameter <code>s<sub>0</sub></code> or
     * <code>s<sub>1</sub></code>.
     * @param vm The Lucas Sequence element <code>V<sub>m</sub></code>.
     * @param a The parameter <code>a</code> of the elliptic curve.
     * @param m The bit length of the finite field
     * <code><b>F</b><sub>m</sub></code>.
     * @param c The number of bits of accuracy, i.e. the scale of the returned
     * <code>SimpleBigDecimal</code>.
     * @return The value <code>λ = s k / n</code> computed to
     * <code>c</code> bits of accuracy.
     */
public static SimpleBigDecimal approximateDivisionByN(BigInteger k, BigInteger s, BigInteger vm, byte a, int m, int c) {
    int _k = (m + 5) / 2 + c;
    BigInteger ns = k.shiftRight(m - _k - 2 + a);
    BigInteger gs = s.multiply(ns);
    BigInteger hs = gs.shiftRight(m);
    BigInteger js = vm.multiply(hs);
    BigInteger gsPlusJs = gs.add(js);
    BigInteger ls = gsPlusJs.shiftRight(_k - c);
    if (gsPlusJs.testBit(_k - c - 1)) {
        // round up
        ls = ls.add(ECConstants.ONE);
    }
    return new SimpleBigDecimal(ls, c);
}

8. Tnaf#approximateDivisionByN()

Project: bitcoin-android
Source File: Tnaf.java
View license
/**
     * Approximate division by <code>n</code>. For an integer
     * <code>k</code>, the value <code>λ = s k / n</code> is
     * computed to <code>c</code> bits of accuracy.
     * @param k The parameter <code>k</code>.
     * @param s The curve parameter <code>s<sub>0</sub></code> or
     * <code>s<sub>1</sub></code>.
     * @param vm The Lucas Sequence element <code>V<sub>m</sub></code>.
     * @param a The parameter <code>a</code> of the elliptic curve.
     * @param m The bit length of the finite field
     * <code><b>F</b><sub>m</sub></code>.
     * @param c The number of bits of accuracy, i.e. the scale of the returned
     * <code>SimpleBigDecimal</code>.
     * @return The value <code>λ = s k / n</code> computed to
     * <code>c</code> bits of accuracy.
     */
public static SimpleBigDecimal approximateDivisionByN(BigInteger k, BigInteger s, BigInteger vm, byte a, int m, int c) {
    int _k = (m + 5) / 2 + c;
    BigInteger ns = k.shiftRight(m - _k - 2 + a);
    BigInteger gs = s.multiply(ns);
    BigInteger hs = gs.shiftRight(m);
    BigInteger js = vm.multiply(hs);
    BigInteger gsPlusJs = gs.add(js);
    BigInteger ls = gsPlusJs.shiftRight(_k - c);
    if (gsPlusJs.testBit(_k - c - 1)) {
        // round up
        ls = ls.add(ECConstants.ONE);
    }
    return new SimpleBigDecimal(ls, c);
}

9. Tnaf#approximateDivisionByN()

Project: Direct-File-Downloader
Source File: Tnaf.java
View license
/**
     * Approximate division by <code>n</code>. For an integer
     * <code>k</code>, the value <code>λ = s k / n</code> is
     * computed to <code>c</code> bits of accuracy.
     * @param k The parameter <code>k</code>.
     * @param s The curve parameter <code>s<sub>0</sub></code> or
     * <code>s<sub>1</sub></code>.
     * @param vm The Lucas Sequence element <code>V<sub>m</sub></code>.
     * @param a The parameter <code>a</code> of the elliptic curve.
     * @param m The bit length of the finite field
     * <code><b>F</b><sub>m</sub></code>.
     * @param c The number of bits of accuracy, i.e. the scale of the returned
     * <code>SimpleBigDecimal</code>.
     * @return The value <code>λ = s k / n</code> computed to
     * <code>c</code> bits of accuracy.
     */
public static SimpleBigDecimal approximateDivisionByN(BigInteger k, BigInteger s, BigInteger vm, byte a, int m, int c) {
    int _k = (m + 5) / 2 + c;
    BigInteger ns = k.shiftRight(m - _k - 2 + a);
    BigInteger gs = s.multiply(ns);
    BigInteger hs = gs.shiftRight(m);
    BigInteger js = vm.multiply(hs);
    BigInteger gsPlusJs = gs.add(js);
    BigInteger ls = gsPlusJs.shiftRight(_k - c);
    if (gsPlusJs.testBit(_k - c - 1)) {
        // round up
        ls = ls.add(ECConstants.ONE);
    }
    return new SimpleBigDecimal(ls, c);
}

10. ECComputer#add()

Project: TLS-Attacker
Source File: ECComputer.java
View license
/**
     * Provides point addition, without infinity check
     * 
     * @param p
     * @param q
     * @return
     * @throws DivisionException
     *             exception thrown if xq=xp, since then we divide with zero
     */
public Point add(Point p, Point q) throws DivisionException {
    BigInteger xp = p.getX();
    BigInteger yp = p.getY();
    BigInteger xq = q.getX();
    BigInteger yq = q.getY();
    if (xq.subtract(xp).mod(curve.getP()).equals(BigInteger.ZERO)) {
        throw new DivisionException("xq was equal to xp (mod p)");
    }
    BigInteger l = ((yq.subtract(yp)).multiply((xq.subtract(xp)).modInverse(curve.getP()))).mod(curve.getP());
    BigInteger xr = l.pow(2).subtract(xp).subtract(xq).mod(curve.getP());
    BigInteger yr = (l.multiply(xp.subtract(xr))).subtract(yp).mod(curve.getP());
    Point ret = new Point(xr, yr);
    return ret;
}

11. JPAKEUtil#calculateZeroKnowledgeProof()

Project: bc-java
Source File: JPAKEUtil.java
View license
/**
     * Calculate a zero knowledge proof of x using Schnorr's signature.
     * The returned array has two elements {g^v, r = v-x*h} for x.
     */
public static BigInteger[] calculateZeroKnowledgeProof(BigInteger p, BigInteger q, BigInteger g, BigInteger gx, BigInteger x, String participantId, Digest digest, SecureRandom random) {
    BigInteger[] zeroKnowledgeProof = new BigInteger[2];
    /* Generate a random v, and compute g^v */
    BigInteger vMin = ZERO;
    BigInteger vMax = q.subtract(ONE);
    BigInteger v = BigIntegers.createRandomInRange(vMin, vMax, random);
    BigInteger gv = g.modPow(v, p);
    // h
    BigInteger h = calculateHashForZeroKnowledgeProof(g, gv, gx, participantId, digest);
    zeroKnowledgeProof[0] = gv;
    // r = v-x*h
    zeroKnowledgeProof[1] = v.subtract(x.multiply(h)).mod(q);
    return zeroKnowledgeProof;
}

12. SM#proofEqualLogs()

Project: ChatSecureAndroid
Source File: SM.java
View license
/**
     * Proof of knowledge of logs with exponents being equal
     *
     * @throws SMException
     */
public static BigInteger[] proofEqualLogs(SMState state, int version) throws SMException {
    BigInteger r = randomExponent();
    /* Compute the value of c, as c = h(g1^r, (Qa/Qb)^r) */
    BigInteger temp1 = state.g1.modPow(r, MODULUS_S);
    BigInteger temp2 = state.qab.modPow(r, MODULUS_S);
    BigInteger c = hash(version, temp1, temp2);
    /* Compute the d values, as d = r - x3 c */
    temp1 = state.x3.multiply(c).mod(ORDER_S);
    BigInteger d = r.subtract(temp1).mod(ORDER_S);
    BigInteger[] ret = new BigInteger[2];
    ret[0] = c;
    ret[1] = d;
    return ret;
}

13. StatsUtils#getHistogramBigInt()

Project: egads
Source File: StatsUtils.java
View license
/**
     * Same as <code>getHistogram</code> but operates on <code>BigIntegers</code>.
     */
public static List<Integer> getHistogramBigInt(List<BigInteger> data, int breaks) {
    if (data.isEmpty()) {
        return Collections.emptyList();
    }
    List<Integer> ret = new ArrayList<Integer>(breaks);
    for (int i = 0; i < breaks; i++) {
        ret.add(0);
    }
    BigInteger min = Collections.min(data);
    BigInteger max = Collections.max(data);
    BigInteger range = max.subtract(min).add(BigInteger.valueOf(1));
    BigInteger step = range.divide(BigInteger.valueOf(breaks));
    if (step.equals(BigInteger.ZERO)) {
        // too small
        return Collections.emptyList();
    }
    for (BigInteger point : data) {
        int index = point.subtract(min).divide(step).intValue();
        // Math.min necessary because rounding error -> AIOOBE
        index = Math.min(index, breaks - 1);
        ret.set(index, ret.get(index) + 1);
    }
    return ret;
}

14. PrimeTest#checkPrime()

Project: openjdk
Source File: PrimeTest.java
View license
/**
     * Verifies whether the fraction of probable primes detected is at least 1 -
     * 1/2^certainty.
     *
     * @return true if and only if the test succeeds
     */
private static boolean checkPrime(Set<BigInteger> primes, int certainty, boolean parallel) {
    long probablePrimes = (parallel ? primes.parallelStream() : primes.stream()).filter( bi -> bi.isProbablePrime(certainty)).count();
    // N = certainty / 2
    // Success if p/t >= 1 - 1/4^N
    // or (p/t)*4^N >= 4^N - 1
    // or p*4^N >= t*(4^N - 1)
    BigInteger p = BigInteger.valueOf(probablePrimes);
    BigInteger t = BigInteger.valueOf(primes.size());
    BigInteger fourToTheC = BigInteger.valueOf(4).pow(certainty / 2);
    BigInteger fourToTheCMinusOne = fourToTheC.subtract(BigInteger.ONE);
    BigInteger left = p.multiply(fourToTheC);
    BigInteger right = t.multiply(fourToTheCMinusOne);
    if (left.compareTo(right) < 0) {
        System.err.println("Probable prime certainty test failed");
    }
    return left.compareTo(right) >= 0;
}

15. MathHelper#extendedEuclid()

Project: TLS-Attacker
Source File: MathHelper.java
View license
/**
     * 
     * @param u
     * @param v
     * @return (c,r,s) such that c = r u + s v
     */
public static BigIntegerTripple extendedEuclid(BigInteger u, BigInteger v) {
    BigInteger r = BigInteger.ONE;
    BigInteger s = BigInteger.ZERO;
    BigInteger c = u;
    BigInteger v1 = BigInteger.ZERO;
    BigInteger v2 = BigInteger.ONE;
    BigInteger v3 = v;
    while (!v3.equals(BigInteger.ZERO)) {
        BigInteger q = c.divide(v3);
        BigInteger t1 = r.subtract(q.multiply(v1));
        BigInteger t2 = s.subtract(q.multiply(v2));
        BigInteger t3 = c.subtract(q.multiply(v3));
        r = v1;
        s = v2;
        c = v3;
        v1 = t1;
        v2 = t2;
        v3 = t3;
    }
    return new BigIntegerTripple(c, r, s);
}

16. JPAKEParticipant#createRound2PayloadToSend()

Project: bc-java
Source File: JPAKEParticipant.java
View license
/**
     * Creates and returns the payload to send to the other participant during round 2.
     * <p>
     * [email protected] #validateRound1PayloadReceived(JPAKERound1Payload)} must be called prior to this method.
     * <p>
     * After execution, the [email protected] #getState() state} will be  [email protected] #STATE_ROUND_2_CREATED}.
     *
     * @throws IllegalStateException if called prior to [email protected] #validateRound1PayloadReceived(JPAKERound1Payload)}, or multiple times
     */
public JPAKERound2Payload createRound2PayloadToSend() {
    if (this.state >= STATE_ROUND_2_CREATED) {
        throw new IllegalStateException("Round2 payload already created for " + this.participantId);
    }
    if (this.state < STATE_ROUND_1_VALIDATED) {
        throw new IllegalStateException("Round1 payload must be validated prior to creating Round2 payload for " + this.participantId);
    }
    BigInteger gA = JPAKEUtil.calculateGA(p, gx1, gx3, gx4);
    BigInteger s = JPAKEUtil.calculateS(password);
    BigInteger x2s = JPAKEUtil.calculateX2s(q, x2, s);
    BigInteger A = JPAKEUtil.calculateA(p, q, gA, x2s);
    BigInteger[] knowledgeProofForX2s = JPAKEUtil.calculateZeroKnowledgeProof(p, q, gA, A, x2s, participantId, digest, random);
    this.state = STATE_ROUND_2_CREATED;
    return new JPAKERound2Payload(participantId, A, knowledgeProofForX2s);
}

17. CramerShoupParametersGenerator#generateParameters()

View license
/**
     * which generates the p and g values from the given parameters, returning
     * the CramerShoupParameters object.
     * <p>
     * Note: can take a while...
     * </p>
     */
public CramerShoupParameters generateParameters() {
    //
    // find a safe prime p where p = 2*q + 1, where p and q are prime.
    //
    BigInteger[] safePrimes = ParametersHelper.generateSafePrimes(size, certainty, random);
    //		BigInteger p = safePrimes[0];
    BigInteger q = safePrimes[1];
    BigInteger g1 = ParametersHelper.selectGenerator(q, random);
    BigInteger g2 = ParametersHelper.selectGenerator(q, random);
    while (g1.equals(g2)) {
        g2 = ParametersHelper.selectGenerator(q, random);
    }
    return new CramerShoupParameters(q, g1, g2, new SHA256Digest());
}

18. JPAKEParticipant#createRound2PayloadToSend()

Project: bc-java
Source File: JPAKEParticipant.java
View license
/**
     * Creates and returns the payload to send to the other participant during round 2.
     * <p>
     * [email protected] #validateRound1PayloadReceived(JPAKERound1Payload)} must be called prior to this method.
     * </p>
     * <p>
     * After execution, the [email protected] #getState() state} will be  [email protected] #STATE_ROUND_2_CREATED}.
     * </p>
     * @throws IllegalStateException if called prior to [email protected] #validateRound1PayloadReceived(JPAKERound1Payload)}, or multiple times
     */
public JPAKERound2Payload createRound2PayloadToSend() {
    if (this.state >= STATE_ROUND_2_CREATED) {
        throw new IllegalStateException("Round2 payload already created for " + this.participantId);
    }
    if (this.state < STATE_ROUND_1_VALIDATED) {
        throw new IllegalStateException("Round1 payload must be validated prior to creating Round2 payload for " + this.participantId);
    }
    BigInteger gA = JPAKEUtil.calculateGA(p, gx1, gx3, gx4);
    BigInteger s = JPAKEUtil.calculateS(password);
    BigInteger x2s = JPAKEUtil.calculateX2s(q, x2, s);
    BigInteger A = JPAKEUtil.calculateA(p, q, gA, x2s);
    BigInteger[] knowledgeProofForX2s = JPAKEUtil.calculateZeroKnowledgeProof(p, q, gA, A, x2s, participantId, digest, random);
    this.state = STATE_ROUND_2_CREATED;
    return new JPAKERound2Payload(participantId, A, knowledgeProofForX2s);
}

19. MemoryRangeCalculator#calculateRequestRange()

Project: binnavi
Source File: MemoryRangeCalculator.java
View license
/**
   * Calculates the range of memory to request from the debug client. For performance reasons this
   * range is different from the range specified by the user.
   *
   * @param offset The start offset of the range according to the user.
   * @param size The number of bytes to request according to the user.
   * @param sectionStart Beginning of the section the offset belongs to.
   * @param sectionEnd End of the section the offset belongs to.
   *
   * @return A pair that contains the real start offset and the real size information of the
   *         request.
   */
public static Pair<IAddress, Integer> calculateRequestRange(final BigInteger offset, final int size, final IAddress sectionStart, final IAddress sectionEnd) {
    // To smoothen scrolling we try to load a range that is at max
    // +- 3 requested ranges.
    final BigInteger availableBefore = offset.subtract(sectionStart.toBigInteger());
    final BigInteger availableAfter = sectionEnd.toBigInteger().subtract(offset).add(BigInteger.ONE);
    final BigInteger loadBefore = availableBefore.compareTo(BigInteger.valueOf(3L * size)) == -1 ? availableBefore : BigInteger.valueOf(3L * size);
    final BigInteger loadAfter = availableAfter.compareTo(BigInteger.valueOf(3L * size)) == -1 ? availableAfter : BigInteger.valueOf(3L * size);
    final BigInteger realOffset = offset.subtract(loadBefore);
    final int realSize = (int) (loadBefore.add(loadAfter)).longValue();
    return new Pair<IAddress, Integer>(new CAddress(realOffset), realSize);
}

20. SM#proofKnowLog()

Project: ChatSecureAndroid
Source File: SM.java
View license
/**
     * Proof of knowledge of a discrete logarithm
     *
     * @throws SMException
     */
public static BigInteger[] proofKnowLog(BigInteger g, BigInteger x, int version) throws SMException {
    BigInteger r = randomExponent();
    BigInteger temp = g.modPow(r, SM.MODULUS_S);
    BigInteger c = hash(version, temp, null);
    temp = x.multiply(c).mod(ORDER_S);
    BigInteger d = r.subtract(temp).mod(ORDER_S);
    BigInteger[] ret = new BigInteger[2];
    ret[0] = c;
    ret[1] = d;
    return ret;
}

21. AbstractConfig#calcDifficulty()

Project: ethereumj
Source File: AbstractConfig.java
View license
@Override
public BigInteger calcDifficulty(BlockHeader curBlock, BlockHeader parent) {
    BigInteger pd = parent.getDifficultyBI();
    BigInteger quotient = pd.divide(getConstants().getDIFFICULTY_BOUND_DIVISOR());
    BigInteger sign = getCalcDifficultyMultiplier(curBlock, parent);
    BigInteger fromParent = pd.add(quotient.multiply(sign));
    BigInteger difficulty = max(getConstants().getMINIMUM_DIFFICULTY(), fromParent);
    int periodCount = (int) (curBlock.getNumber() / getConstants().getEXP_DIFFICULTY_PERIOD());
    if (periodCount > 1) {
        difficulty = max(getConstants().getMINIMUM_DIFFICULTY(), difficulty.add(BigInteger.ONE.shiftLeft(periodCount - 2)));
    }
    return difficulty;
}

22. DSAKeyValueType#convertToPublicKey()

Project: keycloak
Source File: DSAKeyValueType.java
View license
/**
     * Convert to the JDK representation of a DSA Public Key
     *
     * @return
     *
     * @throws org.keycloak.saml.common.exceptions.ProcessingException
     */
public DSAPublicKey convertToPublicKey() throws ProcessingException {
    BigInteger BigY, BigP, BigQ, BigG;
    BigY = new BigInteger(1, massage(Base64.decode(new String(y))));
    BigP = new BigInteger(1, massage(Base64.decode(new String(p))));
    BigQ = new BigInteger(1, massage(Base64.decode(new String(q))));
    BigG = new BigInteger(1, massage(Base64.decode(new String(g))));
    try {
        KeyFactory dsaKeyFactory = KeyFactory.getInstance("dsa");
        DSAPublicKeySpec kspec = new DSAPublicKeySpec(BigY, BigP, BigQ, BigG);
        return (DSAPublicKey) dsaKeyFactory.generatePublic(kspec);
    } catch (Exception e) {
        throw new ProcessingException(e);
    }
}

23. DSAKeyValueType#convertToPrivateKey()

Project: keycloak
Source File: DSAKeyValueType.java
View license
/**
     * Convert to the JDK representation of a DSA Private Key
     *
     * @return
     *
     * @throws ProcessingException
     */
public DSAPrivateKey convertToPrivateKey() throws ProcessingException {
    BigInteger BigY, BigP, BigQ, BigG;
    BigY = new BigInteger(1, massage(Base64.decode(new String(y))));
    BigP = new BigInteger(1, massage(Base64.decode(new String(p))));
    BigQ = new BigInteger(1, massage(Base64.decode(new String(q))));
    BigG = new BigInteger(1, massage(Base64.decode(new String(g))));
    try {
        KeyFactory dsaKeyFactory = KeyFactory.getInstance("dsa");
        DSAPrivateKeySpec kspec = new DSAPrivateKeySpec(BigY, BigP, BigQ, BigG);
        return (DSAPrivateKey) dsaKeyFactory.generatePrivate(kspec);
    } catch (Exception e) {
        throw new ProcessingException(e);
    }
}

24. TokenManagerTest#testMultiToken()

Project: Priam
Source File: TokenManagerTest.java
View license
@Test
public void testMultiToken() {
    int h1 = tokenManager.regionOffset("vijay");
    int h2 = tokenManager.regionOffset("vijay2");
    BigInteger t1 = tokenManager.initialToken(100, 10, h1);
    BigInteger t2 = tokenManager.initialToken(100, 10, h2);
    BigInteger tokendistance = t1.subtract(t2).abs();
    int hashDiffrence = h1 - h2;
    assertEquals(new BigInteger("" + hashDiffrence).abs(), tokendistance);
    BigInteger t3 = tokenManager.initialToken(100, 99, h1);
    BigInteger t4 = tokenManager.initialToken(100, 99, h2);
    tokendistance = t3.subtract(t4).abs();
    assertEquals(new BigInteger("" + hashDiffrence).abs(), tokendistance);
}

25. MathHelper#CRT()

Project: TLS-Attacker
Source File: MathHelper.java
View license
/**
     * Computes Chinese Reminder Theorem: x == congs[i] mod moduli[i]
     * 
     * @param congs
     * @param moduli
     * @return
     */
public static BigInteger CRT(BigInteger[] congs, BigInteger[] moduli) {
    BigInteger prodModuli = BigInteger.ONE;
    for (BigInteger mod : moduli) {
        prodModuli = prodModuli.multiply(mod);
    }
    BigInteger[] M = new BigInteger[moduli.length];
    for (int i = 0; i < moduli.length; i++) {
        M[i] = prodModuli.divide(moduli[i]);
    }
    BigInteger retval = BigInteger.ZERO;
    for (int i = 0; i < moduli.length; i++) {
        // get s value from EEA
        BigInteger tmp = extendedEuclid(moduli[i], M[i]).c;
        retval = retval.add(congs[i].multiply(tmp).multiply(M[i]).mod(prodModuli));
    }
    return retval.mod(prodModuli);
}

26. RangeVisitor#getRanges()

Project: atlasdb
Source File: RangeVisitor.java
View license
private Iterable<MutableRange> getRanges() {
    if (threadCount == 1) {
        return ImmutableList.of(new MutableRange(startRow, endRow, batchSize));
    }
    int length = Math.max(startRow.length, endRow.length);
    length = Math.max(1, length);
    byte[] expandedStartRow = Arrays.copyOf(startRow, length);
    byte[] expandedEndRow = Arrays.copyOf(endRow, length);
    for (int i = endRow.length; i < length; i++) {
        expandedEndRow[i] = (byte) 0xff;
    }
    BigInteger startNum = new BigInteger(1, expandedStartRow);
    BigInteger endNum = new BigInteger(1, expandedEndRow);
    BigInteger step = endNum.subtract(startNum).divide(BigInteger.valueOf(threadCount));
    BigInteger curr = startNum.add(step);
    Collection<MutableRange> ranges = Lists.newArrayListWithCapacity(threadCount);
    ranges.add(new MutableRange(startRow, toBytes(curr, length), batchSize));
    for (int i = 1; i < threadCount - 1; i++) {
        BigInteger next = curr.add(step);
        ranges.add(new MutableRange(toBytes(curr, length), toBytes(next, length), batchSize));
        curr = next;
    }
    ranges.add(new MutableRange(toBytes(curr, length), endRow, batchSize));
    return ranges;
}

27. CramerShoupParametersGenerator#generateParameters()

View license
public CramerShoupParameters generateParameters(DHParameters dhParams) {
    BigInteger p = dhParams.getP();
    BigInteger g1 = dhParams.getG();
    // now we just need a second generator
    BigInteger g2 = ParametersHelper.selectGenerator(p, random);
    while (g1.equals(g2)) {
        g2 = ParametersHelper.selectGenerator(p, random);
    }
    return new CramerShoupParameters(p, g1, g2, new SHA256Digest());
}

28. DHParametersGenerator#generateParameters()

Project: bc-java
Source File: DHParametersGenerator.java
View license
/**
     * which generates the p and g values from the given parameters,
     * returning the DHParameters object.
     * <p>
     * Note: can take a while...
     */
public DHParameters generateParameters() {
    //
    // find a safe prime p where p = 2*q + 1, where p and q are prime.
    //
    BigInteger[] safePrimes = DHParametersHelper.generateSafePrimes(size, certainty, random);
    BigInteger p = safePrimes[0];
    BigInteger q = safePrimes[1];
    BigInteger g = DHParametersHelper.selectGenerator(p, q, random);
    return new DHParameters(p, g, q, TWO, null);
}

29. ElGamalParametersGenerator#generateParameters()

View license
/**
     * which generates the p and g values from the given parameters,
     * returning the ElGamalParameters object.
     * <p>
     * Note: can take a while...
     */
public ElGamalParameters generateParameters() {
    //
    // find a safe prime p where p = 2*q + 1, where p and q are prime.
    //
    BigInteger[] safePrimes = DHParametersHelper.generateSafePrimes(size, certainty, random);
    BigInteger p = safePrimes[0];
    BigInteger q = safePrimes[1];
    BigInteger g = DHParametersHelper.selectGenerator(p, q, random);
    return new ElGamalParameters(p, g);
}

30. RSAKeyEncapsulation#encrypt()

Project: bc-java
Source File: RSAKeyEncapsulation.java
View license
/**
     * Generate and encapsulate a random session key.
     *
     * @param out    the output buffer for the encapsulated key.
     * @param outOff the offset for the output buffer.
     * @param keyLen the length of the random session key.
     * @return the random session key.
     */
public CipherParameters encrypt(byte[] out, int outOff, int keyLen) throws IllegalArgumentException {
    if (key.isPrivate()) {
        throw new IllegalArgumentException("Public key required for encryption");
    }
    BigInteger n = key.getModulus();
    BigInteger e = key.getExponent();
    // Generate the ephemeral random and encode it    
    BigInteger r = BigIntegers.createRandomInRange(ZERO, n.subtract(ONE), rnd);
    // Encrypt the random and encode it     
    BigInteger c = r.modPow(e, n);
    byte[] C = BigIntegers.asUnsignedByteArray((n.bitLength() + 7) / 8, c);
    System.arraycopy(C, 0, out, outOff, C.length);
    return generateKey(n, r, keyLen);
}

31. RSAKeyEncapsulation#decrypt()

Project: bc-java
Source File: RSAKeyEncapsulation.java
View license
/**
     * Decrypt an encapsulated session key.
     *
     * @param in     the input buffer for the encapsulated key.
     * @param inOff  the offset for the input buffer.
     * @param inLen  the length of the encapsulated key.
     * @param keyLen the length of the session key.
     * @return the session key.
     */
public CipherParameters decrypt(byte[] in, int inOff, int inLen, int keyLen) throws IllegalArgumentException {
    if (!key.isPrivate()) {
        throw new IllegalArgumentException("Private key required for decryption");
    }
    BigInteger n = key.getModulus();
    BigInteger d = key.getExponent();
    // Decode the input
    byte[] C = new byte[inLen];
    System.arraycopy(in, inOff, C, 0, C.length);
    BigInteger c = new BigInteger(1, C);
    // Decrypt the ephemeral random and encode it
    BigInteger r = c.modPow(d, n);
    return generateKey(n, r, keyLen);
}

32. GLVTypeBEndomorphism#decomposeScalar()

Project: bc-java
Source File: GLVTypeBEndomorphism.java
View license
public BigInteger[] decomposeScalar(BigInteger k) {
    int bits = parameters.getBits();
    BigInteger b1 = calculateB(k, parameters.getG1(), bits);
    BigInteger b2 = calculateB(k, parameters.getG2(), bits);
    GLVTypeBParameters p = parameters;
    BigInteger a = k.subtract((b1.multiply(p.getV1A())).add(b2.multiply(p.getV2A())));
    BigInteger b = (b1.multiply(p.getV1B())).add(b2.multiply(p.getV2B())).negate();
    return new BigInteger[] { a, b };
}

33. DiscoverEndomorphisms#findBetaValues()

Project: bc-java
Source File: DiscoverEndomorphisms.java
View license
private static ECFieldElement[] findBetaValues(ECCurve c) {
    BigInteger q = c.getField().getCharacteristic();
    BigInteger e = q.divide(ECConstants.THREE);
    // Search for a random value that generates a non-trival cube root of 1
    SecureRandom random = new SecureRandom();
    BigInteger b;
    do {
        BigInteger r = BigIntegers.createRandomInRange(ECConstants.TWO, q.subtract(ECConstants.TWO), random);
        b = r.modPow(e, q);
    } while (b.equals(ECConstants.ONE));
    ECFieldElement beta = c.fromBigInteger(b);
    return new ECFieldElement[] { beta, beta.square() };
}

34. DHTest#testBounds()

Project: bc-java
Source File: DHTest.java
View license
private void testBounds() {
    BigInteger p1 = new BigInteger("00C8028E9151C6B51BCDB35C1F6B2527986A72D8546AE7A4BF41DC4289FF9837EE01592D36C324A0F066149B8B940C86C87D194206A39038AE3396F8E12435BB74449B70222D117B8A2BB77CB0D67A5D664DDE7B75E0FEC13CE0CAF258DAF3ADA0773F6FF0F2051D1859929AAA53B07809E496B582A89C3D7DA8B6E38305626621", 16);
    BigInteger g1 = new BigInteger("1F869713181464577FE4026B47102FA0D7675503A4FCDA810881FAEC3524E6DBAEA9B96561EF7F8BEA76466DF11C2F3EB1A90CC5851735BF860606481257EECE6418C0204E61004E85D7131CE54BCBC7AD67E53C79DCB715E7C8D083DCD85D728283EC8F96839B4C9FA7C0727C472BEB94E4613CAFA8D580119C0AF4BF8AF252", 16);
    int l1 = 1023;
    BigInteger p2 = new BigInteger("00B333C98720220CC3946F494E25231B3E19F9AD5F6B19F4E7ABF80D8826C491C3224D4F7415A14A7C11D1BE584405FED12C3554F103E56A72D986CA5E325BB9DE07AC37D1EAE5E5AC724D32EF638F0E4462D4C1FC7A45B9FD3A5DF5EC36A1FA4DAA3FBB66AA42B1B71DF416AB547E987513426C7BB8634F5F4D37705514FDC1E1", 16);
    BigInteger g2 = new BigInteger("2592F5A99FE46313650CCE66C94C15DBED9F4A45BD05C329986CF5D3E12139F0405A47C6385FEA27BFFEDC4CBABC5BB151F3BEE7CC3D51567F1E2B12A975AA9F48A70BDAAE7F5B87E70ADCF902490A3CBEFEDA41EBA8E12E02B56120B5FDEFBED07F5EAD3AE020DF3C8233216F8F0D35E13A7AE4DA5CBCC0D91EADBF20C281C6", 16);
    int l2 = 1024;
    DHKeyGenerationParameters params1 = new DHKeyGenerationParameters(new SecureRandom(), new DHParameters(p1, g1, null, l1));
    DHKeyGenerationParameters params2 = new DHKeyGenerationParameters(new SecureRandom(), new DHParameters(p2, g2, null, l2));
    DHBasicKeyPairGenerator kpGen = new DHBasicKeyPairGenerator();
    kpGen.init(params1);
    kpGen.init(params2);
}

35. DHParametersGenerator#generateParameters()

View license
/**
     * which generates the p and g values from the given parameters,
     * returning the DHParameters object.
     * <p>
     * Note: can take a while...
     */
public DHParameters generateParameters() {
    //
    // find a safe prime p where p = 2*q + 1, where p and q are prime.
    //
    BigInteger[] safePrimes = DHParametersHelper.generateSafePrimes(size, certainty, random);
    BigInteger p = safePrimes[0];
    BigInteger q = safePrimes[1];
    BigInteger g = DHParametersHelper.selectGenerator(p, q, random);
    return new DHParameters(p, g, q, TWO, null);
}

36. ElGamalParametersGenerator#generateParameters()

View license
/**
     * which generates the p and g values from the given parameters,
     * returning the ElGamalParameters object.
     * <p>
     * Note: can take a while...
     */
public ElGamalParameters generateParameters() {
    //
    // find a safe prime p where p = 2*q + 1, where p and q are prime.
    //
    BigInteger[] safePrimes = DHParametersHelper.generateSafePrimes(size, certainty, random);
    BigInteger p = safePrimes[0];
    BigInteger q = safePrimes[1];
    BigInteger g = DHParametersHelper.selectGenerator(p, q, random);
    return new ElGamalParameters(p, g);
}

37. KEYConverter#parseDSA()

Project: browsermob-proxy
Source File: KEYConverter.java
View license
static DSAPublicKey parseDSA(DataInputStream in) throws IOException {
    byte t = in.readByte();
    BigInteger q = readBigInteger(in, 20);
    BigInteger p = readBigInteger(in, 64 + t * 8);
    BigInteger g = readBigInteger(in, 64 + t * 8);
    BigInteger y = readBigInteger(in, 64 + t * 8);
    DSAPublicKey dsa = new DSAPubKey(p, q, g, y);
    return dsa;
}

38. KEYConverter#buildDSA()

Project: browsermob-proxy
Source File: KEYConverter.java
View license
static byte[] buildDSA(DSAPublicKey key) {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    BigInteger q = key.getParams().getQ();
    BigInteger p = key.getParams().getP();
    BigInteger g = key.getParams().getG();
    BigInteger y = key.getY();
    int t = (p.toByteArray().length - 64) / 8;
    out.write(t);
    writeBigInteger(out, q);
    writeBigInteger(out, p);
    writeBigInteger(out, g);
    writeBigInteger(out, y);
    return out.toByteArray();
}

39. DSASHA1Verify#decodeSSHDSAPublicKey()

Project: connectbot
Source File: DSASHA1Verify.java
View license
public static DSAPublicKey decodeSSHDSAPublicKey(byte[] key) throws IOException {
    TypesReader tr = new TypesReader(key);
    String key_format = tr.readString();
    if (key_format.equals("ssh-dss") == false)
        throw new IllegalArgumentException("This is not a ssh-dss public key!");
    BigInteger p = tr.readMPINT();
    BigInteger q = tr.readMPINT();
    BigInteger g = tr.readMPINT();
    BigInteger y = tr.readMPINT();
    if (tr.remain() != 0)
        throw new IOException("Padding in DSA public key!");
    return new DSAPublicKey(p, q, g, y);
}

40. DSASHA1Verify#generateSignature()

Project: connectbot
Source File: DSASHA1Verify.java
View license
public static DSASignature generateSignature(byte[] message, DSAPrivateKey pk, SecureRandom rnd) {
    SHA1 md = new SHA1();
    md.update(message);
    byte[] sha_message = new byte[md.getDigestLength()];
    md.digest(sha_message);
    BigInteger m = new BigInteger(1, sha_message);
    BigInteger k;
    int qBitLength = pk.getQ().bitLength();
    do {
        k = new BigInteger(qBitLength, rnd);
    } while (k.compareTo(pk.getQ()) >= 0);
    BigInteger r = pk.getG().modPow(k, pk.getP()).mod(pk.getQ());
    k = k.modInverse(pk.getQ()).multiply(m.add((pk).getX().multiply(r)));
    BigInteger s = k.mod(pk.getQ());
    return new DSASignature(r, s);
}

41. TimeUtil#deltaMs()

Project: incubator-htrace
Source File: TimeUtil.java
View license
/**
   * Get the approximate delta between two monotonic times.
   *
   * This function makes the following assumptions:
   * 1. We read startMs from the monotonic clock prior to endMs.
   * 2. The two times are not more than 100 years or so apart.
   *
   * With these two assumptions in hand, we can smooth over some of the
   * unpleasant features of the monotonic clock:
   * 1. It can return either positive or negative values.
   * 2. When the number of nanoseconds reaches Long.MAX_VALUE it wraps around
   * to Long.MIN_VALUE.
   * 3. On some messed up systems it has been known to jump backwards every
   * now and then.  Oops.  CPU core synchronization mumble mumble.
   *
   * @param startMs  The start time.
   * @param endMs    The end time.
   * @return         The delta between the two times.
   */
static long deltaMs(long startMs, long endMs) {
    BigInteger startNs = BigInteger.valueOf(TimeUnit.NANOSECONDS.convert(startMs, TimeUnit.MILLISECONDS));
    BigInteger endNs = BigInteger.valueOf(TimeUnit.NANOSECONDS.convert(endMs, TimeUnit.MILLISECONDS));
    BigInteger deltaNs = endNs.subtract(startNs);
    if (deltaNs.signum() >= 0) {
        return TimeUnit.MILLISECONDS.convert(deltaNs.min(BigInteger.valueOf(Long.MAX_VALUE)).longValue(), TimeUnit.NANOSECONDS);
    }
    deltaNs = deltaNs.negate();
    if (deltaNs.compareTo(BigInteger.valueOf(Long.MAX_VALUE / 2)) < 0) {
        // the name).
        return 0L;
    }
    // Handle rollover.
    BigInteger revDeltaNs = BigInteger.ONE.shiftLeft(64).subtract(deltaNs);
    return TimeUnit.MILLISECONDS.convert(revDeltaNs.min(BigInteger.valueOf(Long.MAX_VALUE)).longValue(), TimeUnit.NANOSECONDS);
}

42. DSASHA1Verify#decodeSSHDSAPublicKey()

View license
public static DSAPublicKey decodeSSHDSAPublicKey(byte[] key) throws IOException {
    TypesReader tr = new TypesReader(key);
    String key_format = tr.readString();
    if (key_format.equals("ssh-dss") == false)
        throw new IllegalArgumentException("This is not a ssh-dss public key!");
    BigInteger p = tr.readMPINT();
    BigInteger q = tr.readMPINT();
    BigInteger g = tr.readMPINT();
    BigInteger y = tr.readMPINT();
    if (tr.remain() != 0)
        throw new IOException("Padding in DSA public key!");
    return new DSAPublicKey(p, q, g, y);
}

43. DSASHA1Verify#generateSignature()

View license
public static DSASignature generateSignature(byte[] message, DSAPrivateKey pk, SecureRandom rnd) {
    SHA1 md = new SHA1();
    md.update(message);
    byte[] sha_message = new byte[md.getDigestLength()];
    md.digest(sha_message);
    BigInteger m = new BigInteger(1, sha_message);
    BigInteger k;
    int qBitLength = pk.getQ().bitLength();
    do {
        k = new BigInteger(qBitLength, rnd);
    } while (k.compareTo(pk.getQ()) >= 0);
    BigInteger r = pk.getG().modPow(k, pk.getP()).mod(pk.getQ());
    k = k.modInverse(pk.getQ()).multiply(m.add((pk).getX().multiply(r)));
    BigInteger s = k.mod(pk.getQ());
    return new DSASignature(r, s);
}

44. BigIntegerModPowTest#testModPowPosExp()

Project: j2objc
Source File: BigIntegerModPowTest.java
View license
/**
	 * modPow: positive exponent
	 */
public void testModPowPosExp() {
    byte aBytes[] = { -127, 100, 56, 7, 98, -1, 39, -128, 127, 75, 48, -7 };
    byte eBytes[] = { 27, -15, 65, 39 };
    byte mBytes[] = { -128, 2, 3, 4, 5 };
    int aSign = 1;
    int eSign = 1;
    int mSign = 1;
    byte rBytes[] = { 113, 100, -84, -28, -85 };
    BigInteger aNumber = new BigInteger(aSign, aBytes);
    BigInteger exp = new BigInteger(eSign, eBytes);
    BigInteger modulus = new BigInteger(mSign, mBytes);
    BigInteger result = aNumber.modPow(exp, modulus);
    byte resBytes[] = new byte[rBytes.length];
    resBytes = result.toByteArray();
    for (int i = 0; i < resBytes.length; i++) {
        assertTrue(resBytes[i] == rBytes[i]);
    }
    assertEquals("incorrect sign", 1, result.signum());
}

45. BigIntegerModPowTest#testModPowNegExp()

Project: j2objc
Source File: BigIntegerModPowTest.java
View license
/**
	 * modPow: negative exponent
	 */
public void testModPowNegExp() {
    byte aBytes[] = { -127, 100, 56, 7, 98, -1, 39, -128, 127, 75, 48, -7 };
    byte eBytes[] = { 27, -15, 65, 39 };
    byte mBytes[] = { -128, 2, 3, 4, 5 };
    int aSign = 1;
    int eSign = -1;
    int mSign = 1;
    byte rBytes[] = { 12, 118, 46, 86, 92 };
    BigInteger aNumber = new BigInteger(aSign, aBytes);
    BigInteger exp = new BigInteger(eSign, eBytes);
    BigInteger modulus = new BigInteger(mSign, mBytes);
    BigInteger result = aNumber.modPow(exp, modulus);
    byte resBytes[] = new byte[rBytes.length];
    resBytes = result.toByteArray();
    for (int i = 0; i < resBytes.length; i++) {
        assertTrue(resBytes[i] == rBytes[i]);
    }
    assertEquals("incorrect sign", 1, result.signum());
}

46. DSA#generateS()

Project: jdk7u-jdk
Source File: DSA.java
View license
private BigInteger generateS(BigInteger x, BigInteger q, BigInteger r, BigInteger k) throws SignatureException {
    byte[] s2 = getDigest();
    BigInteger temp = new BigInteger(1, s2);
    BigInteger k1 = k.modInverse(q);
    BigInteger s = x.multiply(r);
    s = temp.add(s);
    s = k1.multiply(s);
    return s.remainder(q);
}

47. DSSPublicKeyEntryDecoder#decodePublicKey()

View license
@Override
public DSAPublicKey decodePublicKey(String keyType, InputStream keyData) throws IOException, GeneralSecurityException {
    if (!KeyPairProvider.SSH_DSS.equals(keyType)) {
        // just in case we were invoked directly
        throw new InvalidKeySpecException("Unepected key type: " + keyType);
    }
    BigInteger p = decodeBigInt(keyData);
    BigInteger q = decodeBigInt(keyData);
    BigInteger g = decodeBigInt(keyData);
    BigInteger y = decodeBigInt(keyData);
    return generatePublicKey(new DSAPublicKeySpec(y, p, q, g));
}

48. MontgomeryMultiplyTest#montgomeryMultiply()

Project: openjdk
Source File: MontgomeryMultiplyTest.java
View license
// Montgomery multiplication
// Calculate a * b * r^-1 mod n)
//
// R is a power of the word size
// N' = R^-1 mod N
//
// T := ab
// m := (T mod R)N' mod R [so 0 <= m < R]
// t := (T + mN)/R
// if t >= N then return t - N else return t
//
BigInteger montgomeryMultiply(BigInteger a, BigInteger b, BigInteger N, int len, BigInteger n_prime) throws Throwable {
    BigInteger T = a.multiply(b);
    BigInteger R = BigInteger.ONE.shiftLeft(len * 32);
    BigInteger mask = R.subtract(BigInteger.ONE);
    BigInteger m = (T.and(mask)).multiply(n_prime);
    // i.e. m.mod(R)
    m = m.and(mask);
    T = T.add(m.multiply(N));
    // i.e. T.divide(R)
    T = T.shiftRight(len * 32);
    if (T.compareTo(N) > 0) {
        T = T.subtract(N);
    }
    return T;
}

49. Bug6937964Test#testNewDurationDayTimeBigInteger()

Project: openjdk
Source File: Bug6937964Test.java
View license
@Test
public void testNewDurationDayTimeBigInteger() throws DatatypeConfigurationException {
    DatatypeFactory dtf = DatatypeFactory.newInstance();
    BigInteger day = new BigInteger("1");
    BigInteger hour = new BigInteger("23");
    BigInteger min = new BigInteger("59");
    BigInteger sec = new BigInteger("65");
    Duration d = dtf.newDurationDayTime(true, day, hour, min, sec);
    int days = d.getDays();
    System.out.println("Days: " + days);
    Assert.assertTrue(days == 2, "Return value should be normalized");
}

50. HashProvider#hashCarterWegman()

View license
/**
     * @param value the value to be hashed
     * @param m     integer output range [1,size]
     * @param k     number of hashes to be computed
     * @return array with <i>hashes</i> integer hash positions in the range <i>[0,size)</i>
     */
public static int[] hashCarterWegman(byte[] value, int m, int k) {
    int[] positions = new int[k];
    BigInteger prime32 = BigInteger.valueOf(4294967279l);
    BigInteger prime64 = BigInteger.valueOf(53200200938189l);
    BigInteger prime128 = new BigInteger("21213943449988109084994671");
    Random r = new Random(seed32);
    //BigInteger.valueOf(hashBytes(value)
    BigInteger v = new BigInteger(value.length > 0 ? value : new byte[1]);
    for (int i = 0; i < k; i++) {
        BigInteger a = BigInteger.valueOf(r.nextLong());
        BigInteger b = BigInteger.valueOf(r.nextLong());
        positions[i] = a.multiply(v).add(b).mod(prime64).mod(BigInteger.valueOf(m)).intValue();
    }
    return positions;
}

51. KettleTwoWayPasswordEncoder#encryptPassword()

View license
public static final String encryptPassword(String password) {
    if (password == null) {
        return "";
    }
    if (password.length() == 0) {
        return "";
    }
    BigInteger bi_passwd = new BigInteger(password.getBytes());
    BigInteger bi_r0 = new BigInteger(SEED);
    BigInteger bi_r1 = bi_r0.xor(bi_passwd);
    return bi_r1.toString(RADIX);
}

52. TableScanner#makeRanges()

Project: Rhombus
Source File: TableScanner.java
View license
public List<Map.Entry<Long, Long>> makeRanges() {
    Long[] savedStartTokens = this.readSavepoints();
    List<Map.Entry<Long, Long>> ranges = Lists.newArrayList();
    BigInteger fullRange = BigInteger.valueOf(maxToken).subtract(BigInteger.valueOf(minToken)).add(BigInteger.ONE);
    BigInteger rangeLength = fullRange.divide(BigInteger.valueOf(numPartitions));
    BigInteger rangeStart = BigInteger.valueOf(minToken);
    for (int i = 0; i < numPartitions - 1; i++) {
        BigInteger rangeEnd = rangeStart.add(rangeLength).subtract(BigInteger.ONE);
        // If we have a savepoint for this partition, use that start token instead of the default
        if (savedStartTokens != null) {
            rangeStart = BigInteger.valueOf(savedStartTokens[i]);
        }
        AbstractMap.SimpleEntry<Long, Long> range = new AbstractMap.SimpleEntry<Long, Long>(rangeStart.longValue(), rangeEnd.longValue());
        ranges.add(range);
        rangeStart = rangeEnd.add(BigInteger.ONE);
    }
    BigInteger rangeEnd = BigInteger.valueOf(maxToken);
    if (savedStartTokens != null) {
        rangeStart = BigInteger.valueOf(savedStartTokens[numPartitions - 1]);
    }
    AbstractMap.SimpleEntry<Long, Long> range = new AbstractMap.SimpleEntry<Long, Long>(rangeStart.longValue(), rangeEnd.longValue());
    ranges.add(range);
    return ranges;
}

53. BigIntegerModPowTest#testModPowPosExp()

Project: teavm
Source File: BigIntegerModPowTest.java
View license
/**
     * modPow: positive exponent
     */
@Test
public void testModPowPosExp() {
    byte aBytes[] = { -127, 100, 56, 7, 98, -1, 39, -128, 127, 75, 48, -7 };
    byte eBytes[] = { 27, -15, 65, 39 };
    byte mBytes[] = { -128, 2, 3, 4, 5 };
    int aSign = 1;
    int eSign = 1;
    int mSign = 1;
    byte rBytes[] = { 113, 100, -84, -28, -85 };
    BigInteger aNumber = new BigInteger(aSign, aBytes);
    BigInteger exp = new BigInteger(eSign, eBytes);
    BigInteger modulus = new BigInteger(mSign, mBytes);
    BigInteger result = aNumber.modPow(exp, modulus);
    byte resBytes[] = new byte[rBytes.length];
    resBytes = result.toByteArray();
    for (int i = 0; i < resBytes.length; i++) {
        assertTrue(resBytes[i] == rBytes[i]);
    }
    assertEquals("incorrect sign", 1, result.signum());
}

54. BigIntegerModPowTest#testModPowNegExp()

Project: teavm
Source File: BigIntegerModPowTest.java
View license
/**
     * modPow: negative exponent
     */
@Test
public void testModPowNegExp() {
    byte aBytes[] = { -127, 100, 56, 7, 98, -1, 39, -128, 127, 75, 48, -7 };
    byte eBytes[] = { 27, -15, 65, 39 };
    byte mBytes[] = { -128, 2, 3, 4, 5 };
    int aSign = 1;
    int eSign = -1;
    int mSign = 1;
    byte rBytes[] = { 12, 118, 46, 86, 92 };
    BigInteger aNumber = new BigInteger(aSign, aBytes);
    BigInteger exp = new BigInteger(eSign, eBytes);
    BigInteger modulus = new BigInteger(mSign, mBytes);
    BigInteger result = aNumber.modPow(exp, modulus);
    byte resBytes[] = new byte[rBytes.length];
    resBytes = result.toByteArray();
    for (int i = 0; i < resBytes.length; i++) {
        assertTrue(resBytes[i] == rBytes[i]);
    }
    assertEquals("incorrect sign", 1, result.signum());
}

55. MathHelperTest#testCRT()

Project: TLS-Attacker
Source File: MathHelperTest.java
View license
/**
     * Test of CRT method, of class MathHelper.
     */
@Test
public void testCRT() {
    BigInteger[] congs = { new BigInteger("3"), new BigInteger("4"), new BigInteger("5") };
    BigInteger[] moduli = { new BigInteger("2"), new BigInteger("3"), new BigInteger("2") };
    assertEquals(4, MathHelper.CRT(congs, moduli).intValue());
    // computes:
    // x == 2 mod 3
    // x == 3 mod 4
    // x == 1 mod 5
    BigInteger[] congs2 = { new BigInteger("2"), new BigInteger("3"), new BigInteger("1") };
    BigInteger[] moduli2 = { new BigInteger("3"), new BigInteger("4"), new BigInteger("5") };
    assertEquals(11, MathHelper.CRT(congs2, moduli2).intValue());
}

56. SimHashPlusHammingDistanceTextSimilarity#hash()

View license
/**
     * ???????
     * @param word ?
     * @return ???
     */
private BigInteger hash(String word) {
    if (word == null || word.length() == 0) {
        return new BigInteger("0");
    }
    char[] charArray = word.toCharArray();
    BigInteger x = BigInteger.valueOf(((long) charArray[0]) << 7);
    BigInteger m = new BigInteger("1000003");
    BigInteger mask = new BigInteger("2").pow(hashBitCount).subtract(new BigInteger("1"));
    long sum = 0;
    for (char c : charArray) {
        sum += c;
    }
    x = x.multiply(m).xor(BigInteger.valueOf(sum)).and(mask);
    x = x.xor(new BigInteger(String.valueOf(word.length())));
    if (x.equals(new BigInteger("-1"))) {
        x = new BigInteger("-2");
    }
    return x;
}

57. AlbianConfigurtionService#getConfigItemId()

View license
@Override
public BigInteger getConfigItemId(int level) {
    // TODO Auto-generated method stub
    IAlbianRemoteUNIDService ids = AlbianServiceRouter.getService(IAlbianRemoteUNIDService.class, IAlbianRemoteUNIDService.Name);
    if (null == ids) {
        AlbianServiceRouter.getLogger().errorAndThrow(IAlbianLoggerService.AlbianRunningLoggerName, AlbianServiceException.class, "ConfigurtionService is error.", "can not get remoteid-service by name:%s from albian-kernel for configurtion service.", IAlbianRemoteUNIDService.Name);
    }
    BigInteger id = ids.createConfigItemId();
    BigInteger l = new BigInteger(Integer.toString(level));
    BigInteger newid = id.add(l);
    return newid;
}

58. SerializersTest#testBigIntegerSerializer()

Project: astyanax
Source File: SerializersTest.java
View license
@Test
public void testBigIntegerSerializer() {
    BigIntegerSerializer ser = new BigIntegerSerializer();
    BigInteger bi1 = new BigInteger("127");
    ByteBuffer bb1 = ser.toByteBuffer(bi1);
    BigInteger bi1_verify = ser.fromByteBuffer(bb1);
    ByteBuffer bb1_str = ser.fromString("127");
    ByteBuffer bb2 = ser.getNext(bb1);
    BigInteger bi2 = ser.fromByteBuffer(bb2);
    Assert.assertEquals(bi1, bi1_verify);
    Assert.assertEquals(bb1, bb1_str);
    Assert.assertEquals(1, bi2.intValue() - bi1.intValue());
    Assert.assertEquals(bb2.capacity(), bb1.capacity() + 1);
}

59. NaccacheSternEngine#chineseRemainder()

Project: bc-java
Source File: NaccacheSternEngine.java
View license
/**
     * Computes the integer x that is expressed through the given primes and the
     * congruences with the chinese remainder theorem (CRT).
     * 
     * @param congruences
     *            the congruences c_i
     * @param primes
     *            the primes p_i
     * @return an integer x for that x % p_i == c_i
     */
private static BigInteger chineseRemainder(Vector congruences, Vector primes) {
    BigInteger retval = ZERO;
    BigInteger all = ONE;
    for (int i = 0; i < primes.size(); i++) {
        all = all.multiply((BigInteger) primes.elementAt(i));
    }
    for (int i = 0; i < primes.size(); i++) {
        BigInteger a = (BigInteger) primes.elementAt(i);
        BigInteger b = all.divide(a);
        BigInteger b_ = b.modInverse(a);
        BigInteger tmp = b.multiply(b_);
        tmp = tmp.multiply((BigInteger) congruences.elementAt(i));
        retval = retval.add(tmp);
    }
    return retval.mod(all);
}

60. RSABlindingFactorGenerator#generateBlindingFactor()

View license
/**
     * Generate a suitable blind factor for the public key the generator was initialised with.
     *
     * @return a random blind factor
     */
public BigInteger generateBlindingFactor() {
    if (key == null) {
        throw new IllegalStateException("generator not initialised");
    }
    BigInteger m = key.getModulus();
    // must be less than m.bitLength()
    int length = m.bitLength() - 1;
    BigInteger factor;
    BigInteger gcd;
    do {
        factor = new BigInteger(length, random);
        gcd = factor.gcd(m);
    } while (factor.equals(ZERO) || factor.equals(ONE) || !gcd.equals(ONE));
    return factor;
}

61. GLVMultiplier#multiplyPositive()

Project: bc-java
Source File: GLVMultiplier.java
View license
protected ECPoint multiplyPositive(ECPoint p, BigInteger k) {
    if (!curve.equals(p.getCurve())) {
        throw new IllegalStateException();
    }
    BigInteger n = p.getCurve().getOrder();
    BigInteger[] ab = glvEndomorphism.decomposeScalar(k.mod(n));
    BigInteger a = ab[0], b = ab[1];
    ECPointMap pointMap = glvEndomorphism.getPointMap();
    if (glvEndomorphism.hasEfficientPointMap()) {
        return ECAlgorithms.implShamirsTrickWNaf(p, a, pointMap, b);
    }
    return ECAlgorithms.implShamirsTrickWNaf(p, a, pointMap.map(p), b);
}

62. Tnaf#getSi()

Project: bc-java
Source File: Tnaf.java
View license
/**
     * Computes the auxiliary values <code>s<sub>0</sub></code> and
     * <code>s<sub>1</sub></code> used for partial modular reduction. 
     * @param curve The elliptic curve for which to compute
     * <code>s<sub>0</sub></code> and <code>s<sub>1</sub></code>.
     * @throws IllegalArgumentException if <code>curve</code> is not a
     * Koblitz curve (Anomalous Binary Curve, ABC).
     */
public static BigInteger[] getSi(ECCurve.AbstractF2m curve) {
    if (!curve.isKoblitz()) {
        throw new IllegalArgumentException("si is defined for Koblitz curves only");
    }
    int m = curve.getFieldSize();
    int a = curve.getA().toBigInteger().intValue();
    byte mu = getMu(a);
    int shifts = getShiftsForCofactor(curve.getCofactor());
    int index = m + 3 - a;
    BigInteger[] ui = getLucas(mu, index, false);
    if (mu == 1) {
        ui[0] = ui[0].negate();
        ui[1] = ui[1].negate();
    }
    BigInteger dividend0 = ECConstants.ONE.add(ui[1]).shiftRight(shifts);
    BigInteger dividend1 = ECConstants.ONE.add(ui[0]).shiftRight(shifts).negate();
    return new BigInteger[] { dividend0, dividend1 };
}

63. Tnaf#getSi()

Project: bc-java
Source File: Tnaf.java
View license
public static BigInteger[] getSi(int fieldSize, int curveA, BigInteger cofactor) {
    byte mu = getMu(curveA);
    int shifts = getShiftsForCofactor(cofactor);
    int index = fieldSize + 3 - curveA;
    BigInteger[] ui = getLucas(mu, index, false);
    if (mu == 1) {
        ui[0] = ui[0].negate();
        ui[1] = ui[1].negate();
    }
    BigInteger dividend0 = ECConstants.ONE.add(ui[1]).shiftRight(shifts);
    BigInteger dividend1 = ECConstants.ONE.add(ui[0]).shiftRight(shifts).negate();
    return new BigInteger[] { dividend0, dividend1 };
}

64. DiscoverEndomorphisms#isShorter()

Project: bc-java
Source File: DiscoverEndomorphisms.java
View license
private static boolean isShorter(BigInteger[] u, BigInteger[] v) {
    BigInteger u1 = u[0].abs(), u2 = u[1].abs(), v1 = v[0].abs(), v2 = v[1].abs();
    // TODO Check whether "shorter" just means by rectangle norm:
    // return u1.max(u2).compareTo(v1.max(v2)) < 0;
    boolean c1 = u1.compareTo(v1) < 0, c2 = u2.compareTo(v2) < 0;
    if (c1 == c2) {
        return c1;
    }
    BigInteger du = u1.multiply(u1).add(u2.multiply(u2));
    BigInteger dv = v1.multiply(v1).add(v2.multiply(v2));
    return du.compareTo(dv) < 0;
}

65. WNafUtil#getNafWeight()

Project: bc-java
Source File: WNafUtil.java
View license
public static int getNafWeight(BigInteger k) {
    if (k.signum() == 0) {
        return 0;
    }
    BigInteger _3k = k.shiftLeft(1).add(k);
    BigInteger diff = _3k.xor(k);
    return diff.bitCount();
}

66. Primes#isMRProbablePrimeToBase()

Project: bc-java
Source File: Primes.java
View license
/**
     * FIPS 186-4 C.3.1 Miller-Rabin Probabilistic Primality Test (to a fixed base).
     *
     * Run a single iteration of the Miller-Rabin algorithm against the specified base.
     *
     * @param candidate
     *            the [email protected] BigInteger} instance to test for primality.
     * @param base
     *            the base value to use for this iteration.
     * @return <code>false</code> if the specified base is a witness to compositeness (so
     *         <code>candidate</code> is definitely NOT prime), or else <code>true</code>.
     */
public static boolean isMRProbablePrimeToBase(BigInteger candidate, BigInteger base) {
    checkCandidate(candidate, "candidate");
    checkCandidate(base, "base");
    if (base.compareTo(candidate.subtract(ONE)) >= 0) {
        throw new IllegalArgumentException("'base' must be < ('candidate' - 1)");
    }
    if (candidate.bitLength() == 2) {
        return true;
    }
    BigInteger w = candidate;
    BigInteger wSubOne = candidate.subtract(ONE);
    int a = wSubOne.getLowestSetBit();
    BigInteger m = wSubOne.shiftRight(a);
    return implMRProbablePrimeToBase(w, wSubOne, m, a, base);
}

67. IntegerFunctions#extgcd()

Project: bc-java
Source File: IntegerFunctions.java
View license
/**
     * Extended euclidian algorithm (computes gcd and representation).
     *
     * @param a - the first integer
     * @param b - the second integer
     * @return <tt>(d,u,v)</tt>, where <tt>d = gcd(a,b) = ua + vb</tt>
     */
public static BigInteger[] extgcd(BigInteger a, BigInteger b) {
    BigInteger u = ONE;
    BigInteger v = ZERO;
    BigInteger d = a;
    if (b.signum() != 0) {
        BigInteger v1 = ZERO;
        BigInteger v3 = b;
        while (v3.signum() != 0) {
            BigInteger[] tmp = d.divideAndRemainder(v3);
            BigInteger q = tmp[0];
            BigInteger t3 = tmp[1];
            BigInteger t1 = u.subtract(q.multiply(v1));
            u = v1;
            d = v3;
            v1 = t1;
            v3 = t3;
        }
        v = d.subtract(a.multiply(u)).divide(b);
    }
    return new BigInteger[] { d, u, v };
}

68. ModularResultant#combineRho()

Project: bc-java
Source File: ModularResultant.java
View license
/**
     * Calculates a <code>rho</code> modulo <code>m1*m2</code> from
     * two resultants whose <code>rho</code>s are modulo <code>m1</code> and <code>m2</code>.<br/>
     * </code>res</code> is set to <code>null</code>.
     *
     * @param modRes1
     * @param modRes2
     * @return <code>rho</code> modulo <code>modRes1.modulus * modRes2.modulus</code>, and <code>null</code> for </code>res</code>.
     */
static ModularResultant combineRho(ModularResultant modRes1, ModularResultant modRes2) {
    BigInteger mod1 = modRes1.modulus;
    BigInteger mod2 = modRes2.modulus;
    BigInteger prod = mod1.multiply(mod2);
    BigIntEuclidean er = BigIntEuclidean.calculate(mod2, mod1);
    BigIntPolynomial rho1 = (BigIntPolynomial) modRes1.rho.clone();
    rho1.mult(er.x.multiply(mod2));
    BigIntPolynomial rho2 = (BigIntPolynomial) modRes2.rho.clone();
    rho2.mult(er.y.multiply(mod1));
    rho1.add(rho2);
    rho1.mod(prod);
    return new ModularResultant(rho1, null, prod);
}

69. JcaPublicKeyConverter#getParams()

Project: bc-java
Source File: JcaPublicKeyConverter.java
View license
private ECParameterSpec getParams(ECDSAPublicKey key) {
    if (!key.hasParameters()) {
        throw new IllegalArgumentException("Public key does not contains EC Params");
    }
    BigInteger p = key.getPrimeModulusP();
    ECCurve.Fp curve = new ECCurve.Fp(p, key.getFirstCoefA(), key.getSecondCoefB(), key.getOrderOfBasePointR(), key.getCofactorF());
    ECPoint G = curve.decodePoint(key.getBasePointG());
    BigInteger order = key.getOrderOfBasePointR();
    BigInteger coFactor = key.getCofactorF();
    EllipticCurve jcaCurve = convertCurve(curve);
    return new ECParameterSpec(jcaCurve, new java.security.spec.ECPoint(G.getAffineXCoord().toBigInteger(), G.getAffineYCoord().toBigInteger()), order, coFactor.intValue());
}

70. JcaPublicKeyConverter#getParams()

Project: bc-java
Source File: JcaPublicKeyConverter.java
View license
private ECParameterSpec getParams(ECDSAPublicKey key) {
    if (!key.hasParameters()) {
        throw new IllegalArgumentException("Public key does not contains EC Params");
    }
    BigInteger p = key.getPrimeModulusP();
    ECCurve.Fp curve = new ECCurve.Fp(p, key.getFirstCoefA(), key.getSecondCoefB());
    ECPoint G = curve.decodePoint(key.getBasePointG());
    BigInteger order = key.getOrderOfBasePointR();
    BigInteger coFactor = key.getCofactorF();
    ECParameterSpec ecspec = new ECParameterSpec(curve, G, order, coFactor);
    return ecspec;
}

71. FilePatternBlockTest#rangeChecks()

View license
private void rangeChecks(String pattern, String[] elements, boolean numeric) {
    FilePatternBlock block = new FilePatternBlock(pattern);
    int radix = numeric ? 10 : Character.MAX_RADIX;
    BigInteger first = new BigInteger(elements[0], radix);
    BigInteger last = new BigInteger(elements[elements.length - 1], radix);
    BigInteger step;
    try {
        step = new BigInteger(elements[1], radix).subtract(first);
    } catch (ArrayIndexOutOfBoundsException e) {
        step = new BigInteger("1");
    }
    assertTrue(block.getFirst().equals(first));
    assertTrue(block.getLast().equals(last));
    assertTrue(block.getStep().equals(step));
}

72. NaccacheSternEngine#chineseRemainder()

View license
/**
     * Computes the integer x that is expressed through the given primes and the
     * congruences with the chinese remainder theorem (CRT).
     * 
     * @param congruences
     *            the congruences c_i
     * @param primes
     *            the primes p_i
     * @return an integer x for that x % p_i == c_i
     */
private static BigInteger chineseRemainder(Vector congruences, Vector primes) {
    BigInteger retval = ZERO;
    BigInteger all = ONE;
    for (int i = 0; i < primes.size(); i++) {
        all = all.multiply((BigInteger) primes.elementAt(i));
    }
    for (int i = 0; i < primes.size(); i++) {
        BigInteger a = (BigInteger) primes.elementAt(i);
        BigInteger b = all.divide(a);
        BigInteger b_ = b.modInverse(a);
        BigInteger tmp = b.multiply(b_);
        tmp = tmp.multiply((BigInteger) congruences.elementAt(i));
        retval = retval.add(tmp);
    }
    return retval.mod(all);
}

73. RSABlindingFactorGenerator#generateBlindingFactor()

View license
/**
     * Generate a suitable blind factor for the public key the generator was initialised with.
     *
     * @return a random blind factor
     */
public BigInteger generateBlindingFactor() {
    if (key == null) {
        throw new IllegalStateException("generator not initialised");
    }
    BigInteger m = key.getModulus();
    // must be less than m.bitLength()
    int length = m.bitLength() - 1;
    BigInteger factor;
    BigInteger gcd;
    do {
        factor = new BigInteger(length, random);
        gcd = factor.gcd(m);
    } while (factor.equals(ZERO) || factor.equals(ONE) || !gcd.equals(ONE));
    return factor;
}

74. ccn_verify#debugSig()

Project: ccnx
Source File: ccn_verify.java
View license
public static void debugSig(PublicKey pubKey, byte[] signature) {
    if (!(pubKey instanceof RSAPublicKey)) {
        return;
    }
    // take it apart
    RSAPublicKey rsaKey = (RSAPublicKey) pubKey;
    BigInteger sigInt = new BigInteger(1, signature);
    BigInteger sigSigInt = new BigInteger(signature);
    System.out.println("Signature length " + signature.length + " sign? " + sigSigInt.signum());
    BigInteger paddedMessage = sigInt.modPow(rsaKey.getPublicExponent(), rsaKey.getModulus());
    System.out.println("\nSignature: " + DataUtils.printHexBytes(signature) + "\n");
    System.out.println("Inverted signature: " + DataUtils.printHexBytes(paddedMessage.toByteArray()) + "\n");
    if (sigSigInt.signum() < 0) {
        BigInteger paddedSignedMessage = sigSigInt.modPow(rsaKey.getPublicExponent(), rsaKey.getModulus());
        System.out.println("Inverted signed signature: " + DataUtils.printHexBytes(paddedSignedMessage.toByteArray()) + "\n");
    }
}

75. JexlArithmetic#multiply()

Project: commons-jexl
Source File: JexlArithmetic.java
View license
/**
     * Multiply the left value by the right.
     *
     * @param left  left argument
     * @param right  right argument
     * @return left * right.
     */
public Object multiply(Object left, Object right) {
    if (left == null && right == null) {
        return controlNullNullOperands();
    }
    // if either are bigdecimal use that type
    if (left instanceof BigDecimal || right instanceof BigDecimal) {
        BigDecimal l = toBigDecimal(left);
        BigDecimal r = toBigDecimal(right);
        BigDecimal result = l.multiply(r, getMathContext());
        return narrowBigDecimal(left, right, result);
    }
    // if either are floating point (double or float) use double
    if (isFloatingPointNumber(left) || isFloatingPointNumber(right)) {
        double l = toDouble(left);
        double r = toDouble(right);
        return l * r;
    }
    // otherwise treat as integers
    BigInteger l = toBigInteger(left);
    BigInteger r = toBigInteger(right);
    BigInteger result = l.multiply(r);
    return narrowBigInteger(left, right, result);
}

76. JexlArithmetic#subtract()

Project: commons-jexl
Source File: JexlArithmetic.java
View license
/**
     * Subtract the right value from the left.
     *
     * @param left  left argument
     * @param right  right argument
     * @return left - right.
     */
public Object subtract(Object left, Object right) {
    if (left == null && right == null) {
        return controlNullNullOperands();
    }
    // if either are bigdecimal use that type
    if (left instanceof BigDecimal || right instanceof BigDecimal) {
        BigDecimal l = toBigDecimal(left);
        BigDecimal r = toBigDecimal(right);
        BigDecimal result = l.subtract(r, getMathContext());
        return narrowBigDecimal(left, right, result);
    }
    // if either are floating point (double or float) use double
    if (isFloatingPointNumber(left) || isFloatingPointNumber(right)) {
        double l = toDouble(left);
        double r = toDouble(right);
        return l - r;
    }
    // otherwise treat as integers
    BigInteger l = toBigInteger(left);
    BigInteger r = toBigInteger(right);
    BigInteger result = l.subtract(r);
    return narrowBigInteger(left, right, result);
}

77. ENTest#slow_mul()

Project: erjang
Source File: ENTest.java
View license
ENumber slow_mul(int i1, int i2) {
    BigInteger b1 = BigInteger.valueOf(i1);
    BigInteger b2 = BigInteger.valueOf(i2);
    BigInteger res = b1.multiply(b2);
    if (res.compareTo(INT_MIN) < 0)
        return new EBig(res);
    if (res.compareTo(INT_MAX) > 0)
        return new EBig(res);
    assertEquals(res, BigInteger.valueOf(res.intValue()));
    return new ESmall(res.intValue());
}

78. DSAGroup#create()

Project: fred
Source File: DSAGroup.java
View license
public static DSAGroup create(SimpleFieldSet fs) throws IllegalBase64Exception, FSParseException {
    String myP = fs.get("p");
    String myQ = fs.get("q");
    String myG = fs.get("g");
    if (myP == null || myQ == null || myG == null)
        throw new FSParseException("The given SFS doesn't contain required fields!");
    BigInteger p = new BigInteger(1, Base64.decode(myP));
    BigInteger q = new BigInteger(1, Base64.decode(myQ));
    BigInteger g = new BigInteger(1, Base64.decode(myG));
    DSAGroup dg = new DSAGroup(p, q, g);
    if (dg.equals(Global.DSAgroupBigA))
        return Global.DSAgroupBigA;
    return dg;
}

79. UnboundedHilbertSFCOperations#getMinimumQuadSize()

View license
/***
	 * Returns the smallest range that will be fully decomposed (i.e.
	 * decomposition stops when the range is equal or smaller than this value).
	 * Values is based on the _maximumRangeDecompsed and _minRangeDecompsed
	 * instance members.
	 * 
	 * @param minRangeList
	 *            minimum values for each dimension (ordered)
	 * @param maxRangeList
	 *            maximum values for each dimension (ordered)
	 * @return largest range that will be fully decomposed
	 */
private BigInteger getMinimumQuadSize(final List<BigInteger> minRangeList, final List<BigInteger> maxRangeList) {
    BigInteger maxRange = BigInteger.valueOf(1);
    final int dimensionality = Math.min(minRangeList.size(), maxRangeList.size());
    for (int d = 0; d < dimensionality; d++) {
        maxRange = maxRange.max(maxRangeList.get(d).subtract(minRangeList.get(d)).abs().add(BigInteger.ONE));
    }
    final BigInteger maxRangeDecomposed = maxRange.pow(dimensionality);
    if (maxRangeDecomposed.compareTo(UNIT_CELL_SIZE) <= 0) {
        return BigInteger.ONE;
    }
    return maxRangeDecomposed.divide(UNIT_CELL_SIZE);
}

80. RowRangeDataStatistics#compare()

Project: geowave
Source File: RowRangeDataStatistics.java
View license
private int compare(final byte[] a, final byte[] b, final int cardinality) {
    final BigInteger one = toInteger(a, cardinality);
    final BigInteger two = toInteger(b, cardinality);
    return one.compareTo(two);
}

81. GeoWaveAccumuloRecordReader#getProgressForRange()

View license
private static float getProgressForRange(final ByteSequence start, final ByteSequence end, final ByteSequence position) {
    final int maxDepth = Math.min(Math.max(end.length(), start.length()), position.length());
    final BigInteger startBI = new BigInteger(AccumuloMRUtils.extractBytes(start, maxDepth));
    final BigInteger endBI = new BigInteger(AccumuloMRUtils.extractBytes(end, maxDepth));
    final BigInteger positionBI = new BigInteger(AccumuloMRUtils.extractBytes(position, maxDepth));
    return (float) (positionBI.subtract(startBI).doubleValue() / endBI.subtract(startBI).doubleValue());
}

82. UnsignedLongTest#testValueOfBigInteger()

Project: guava
Source File: UnsignedLongTest.java
View license
public void testValueOfBigInteger() {
    BigInteger min = BigInteger.ZERO;
    BigInteger max = UnsignedLong.MAX_VALUE.bigIntegerValue();
    for (BigInteger big : TEST_BIG_INTEGERS) {
        boolean expectSuccess = big.compareTo(min) >= 0 && big.compareTo(max) <= 0;
        try {
            assertEquals(big, UnsignedLong.valueOf(big).bigIntegerValue());
            assertTrue(expectSuccess);
        } catch (IllegalArgumentException e) {
            assertFalse(expectSuccess);
        }
    }
}

83. SetFunction#getLongSum()

Project: h-store
Source File: SetFunction.java
View license
BigInteger getLongSum() {
    BigInteger biglo = BigInteger.valueOf(lo);
    BigInteger bighi = BigInteger.valueOf(hi);
    BigInteger result = (bighi.multiply(multiplier)).add(biglo);
    /*
            if ( result.compareTo(bigint) != 0 ){
                 throw Trace.error(Trace.GENERAL_ERROR, "longSum mismatch");
            }
*/
    return result;
}

84. ExecutionParametersTest#roundTripBigInteger()

Project: isis
Source File: ExecutionParametersTest.java
View license
@Test
public void roundTripBigInteger() throws Exception {
    // given
    final BigInteger value = new BigInteger("123456789123456789");
    // when
    executionParameters.setParameter("test", value);
    final BigInteger roundTripped = executionParameters.getParameterAsBigInteger("test");
    final BigInteger roundTrippedAsT = executionParameters.getParameterAsT("test", BigInteger.class);
    // then
    assertThat(roundTripped, is(value));
    assertThat(roundTrippedAsT, is(value));
}

85. RSAKeyTest#test_getModulus()

Project: j2objc
Source File: RSAKeyTest.java
View license
/**
     * java.security.interfaces.RSAKey
     * #getModulus()
     * test covers following use cases
     *   Case 1: check private key
     *   Case 2: check public key
     */
public void test_getModulus() throws Exception {
    KeyFactory gen = KeyFactory.getInstance("RSA");
    final BigInteger n = BigInteger.valueOf(3233);
    final BigInteger d = BigInteger.valueOf(2753);
    final BigInteger e = BigInteger.valueOf(17);
    RSAKey key = null;
    // Case 1: check private key
    key = (RSAKey) gen.generatePrivate(new RSAPrivateKeySpec(n, d));
    assertEquals("invalid modulus", n, key.getModulus());
    // Case 2: check public key
    key = (RSAKey) gen.generatePublic(new RSAPublicKeySpec(n, e));
    assertEquals("invalid modulus", n, key.getModulus());
}

86. BigIntegerAddTest#testCase1()

Project: j2objc
Source File: BigIntegerAddTest.java
View license
/**
     * Add two positive numbers of the same length
     */
public void testCase1() {
    byte aBytes[] = { 1, 2, 3, 4, 5, 6, 7, 1, 2, 3 };
    byte bBytes[] = { 10, 20, 30, 40, 50, 60, 70, 10, 20, 30 };
    int aSign = 1;
    int bSign = 1;
    byte rBytes[] = { 11, 22, 33, 44, 55, 66, 77, 11, 22, 33 };
    BigInteger aNumber = new BigInteger(aSign, aBytes);
    BigInteger bNumber = new BigInteger(bSign, bBytes);
    BigInteger result = aNumber.add(bNumber);
    byte resBytes[] = new byte[rBytes.length];
    resBytes = result.toByteArray();
    for (int i = 0; i < resBytes.length; i++) {
        assertTrue(resBytes[i] == rBytes[i]);
    }
    assertEquals("incorrect sign", 1, result.signum());
}

87. BigIntegerAddTest#testCase2()

Project: j2objc
Source File: BigIntegerAddTest.java
View license
/**
     * Add two negative numbers of the same length
     */
public void testCase2() {
    byte aBytes[] = { 1, 2, 3, 4, 5, 6, 7, 1, 2, 3 };
    byte bBytes[] = { 10, 20, 30, 40, 50, 60, 70, 10, 20, 30 };
    int aSign = -1;
    int bSign = -1;
    byte rBytes[] = { -12, -23, -34, -45, -56, -67, -78, -12, -23, -33 };
    BigInteger aNumber = new BigInteger(aSign, aBytes);
    BigInteger bNumber = new BigInteger(bSign, bBytes);
    BigInteger result = aNumber.add(bNumber);
    byte resBytes[] = new byte[rBytes.length];
    resBytes = result.toByteArray();
    for (int i = 0; i < resBytes.length; i++) {
        assertTrue(resBytes[i] == rBytes[i]);
    }
    assertEquals("incorrect sign", -1, result.signum());
}

88. BigIntegerAddTest#testCase3()

Project: j2objc
Source File: BigIntegerAddTest.java
View license
/**
     * Add two numbers of the same length.
     * The first one is positive and the second is negative.
     * The first one is greater in absolute value.
     */
public void testCase3() {
    byte aBytes[] = { 3, 4, 5, 6, 7, 8, 9 };
    byte bBytes[] = { 1, 2, 3, 4, 5, 6, 7 };
    byte rBytes[] = { 2, 2, 2, 2, 2, 2, 2 };
    int aSign = 1;
    int bSign = -1;
    BigInteger aNumber = new BigInteger(aSign, aBytes);
    BigInteger bNumber = new BigInteger(bSign, bBytes);
    BigInteger result = aNumber.add(bNumber);
    byte resBytes[] = new byte[rBytes.length];
    resBytes = result.toByteArray();
    for (int i = 0; i < resBytes.length; i++) {
        assertTrue(resBytes[i] == rBytes[i]);
    }
    assertEquals("incorrect sign", 1, result.signum());
}

89. BigIntegerAddTest#testCase4()

Project: j2objc
Source File: BigIntegerAddTest.java
View license
/**
     * Add two numbers of the same length.
     * The first one is negative and the second is positive.
     * The first one is greater in absolute value.
     */
public void testCase4() {
    byte aBytes[] = { 3, 4, 5, 6, 7, 8, 9 };
    byte bBytes[] = { 1, 2, 3, 4, 5, 6, 7 };
    byte rBytes[] = { -3, -3, -3, -3, -3, -3, -2 };
    int aSign = -1;
    int bSign = 1;
    BigInteger aNumber = new BigInteger(aSign, aBytes);
    BigInteger bNumber = new BigInteger(bSign, bBytes);
    BigInteger result = aNumber.add(bNumber);
    byte resBytes[] = new byte[rBytes.length];
    resBytes = result.toByteArray();
    for (int i = 0; i < resBytes.length; i++) {
        assertTrue(resBytes[i] == rBytes[i]);
    }
    assertEquals("incorrect sign", -1, result.signum());
}

90. BigIntegerAddTest#testCase5()

Project: j2objc
Source File: BigIntegerAddTest.java
View license
/**
     * Add two numbers of the same length.
     * The first is positive and the second is negative.
     * The first is less in absolute value.
     */
public void testCase5() {
    byte aBytes[] = { 1, 2, 3, 4, 5, 6, 7 };
    byte bBytes[] = { 3, 4, 5, 6, 7, 8, 9 };
    byte rBytes[] = { -3, -3, -3, -3, -3, -3, -2 };
    int aSign = 1;
    int bSign = -1;
    BigInteger aNumber = new BigInteger(aSign, aBytes);
    BigInteger bNumber = new BigInteger(bSign, bBytes);
    BigInteger result = aNumber.add(bNumber);
    byte resBytes[] = new byte[rBytes.length];
    resBytes = result.toByteArray();
    for (int i = 0; i < resBytes.length; i++) {
        assertTrue(resBytes[i] == rBytes[i]);
    }
    assertEquals("incorrect sign", -1, result.signum());
}

91. BigIntegerAddTest#testCase6()

Project: j2objc
Source File: BigIntegerAddTest.java
View license
/**
     * Add two numbers of the same length.
     * The first one is negative and the second is positive.
     * The first one is less in absolute value.
     */
public void testCase6() {
    byte aBytes[] = { 1, 2, 3, 4, 5, 6, 7 };
    byte bBytes[] = { 3, 4, 5, 6, 7, 8, 9 };
    byte rBytes[] = { 2, 2, 2, 2, 2, 2, 2 };
    int aSign = -1;
    int bSign = 1;
    BigInteger aNumber = new BigInteger(aSign, aBytes);
    BigInteger bNumber = new BigInteger(bSign, bBytes);
    BigInteger result = aNumber.add(bNumber);
    byte resBytes[] = new byte[rBytes.length];
    resBytes = result.toByteArray();
    for (int i = 0; i < resBytes.length; i++) {
        assertTrue(resBytes[i] == rBytes[i]);
    }
    assertEquals("incorrect sign", 1, result.signum());
}

92. BigIntegerAddTest#testCase7()

Project: j2objc
Source File: BigIntegerAddTest.java
View license
/**
     * Add two positive numbers of different length.
     * The first is longer.
     */
public void testCase7() {
    byte aBytes[] = { 1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7 };
    byte bBytes[] = { 10, 20, 30, 40, 50, 60, 70, 10, 20, 30 };
    int aSign = 1;
    int bSign = 1;
    byte rBytes[] = { 1, 2, 3, 4, 15, 26, 37, 41, 52, 63, 74, 15, 26, 37 };
    BigInteger aNumber = new BigInteger(aSign, aBytes);
    BigInteger bNumber = new BigInteger(bSign, bBytes);
    BigInteger result = aNumber.add(bNumber);
    byte resBytes[] = new byte[rBytes.length];
    resBytes = result.toByteArray();
    for (int i = 0; i < resBytes.length; i++) {
        assertTrue(resBytes[i] == rBytes[i]);
    }
    assertEquals("incorrect sign", 1, result.signum());
}

93. BigIntegerAddTest#testCase8()

Project: j2objc
Source File: BigIntegerAddTest.java
View license
/**
     * Add two positive numbers of different length.
     * The second is longer.
     */
public void testCase8() {
    byte aBytes[] = { 10, 20, 30, 40, 50, 60, 70, 10, 20, 30 };
    byte bBytes[] = { 1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7 };
    byte rBytes[] = { 1, 2, 3, 4, 15, 26, 37, 41, 52, 63, 74, 15, 26, 37 };
    BigInteger aNumber = new BigInteger(aBytes);
    BigInteger bNumber = new BigInteger(bBytes);
    BigInteger result = aNumber.add(bNumber);
    byte resBytes[] = new byte[rBytes.length];
    resBytes = result.toByteArray();
    for (int i = 0; i < resBytes.length; i++) {
        assertTrue(resBytes[i] == rBytes[i]);
    }
    assertEquals("incorrect sign", 1, result.signum());
}

94. BigIntegerAddTest#testCase9()

Project: j2objc
Source File: BigIntegerAddTest.java
View license
/**
     * Add two negative numbers of different length.
     * The first is longer.
     */
public void testCase9() {
    byte aBytes[] = { 1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7 };
    byte bBytes[] = { 10, 20, 30, 40, 50, 60, 70, 10, 20, 30 };
    int aSign = -1;
    int bSign = -1;
    byte rBytes[] = { -2, -3, -4, -5, -16, -27, -38, -42, -53, -64, -75, -16, -27, -37 };
    BigInteger aNumber = new BigInteger(aSign, aBytes);
    BigInteger bNumber = new BigInteger(bSign, bBytes);
    BigInteger result = aNumber.add(bNumber);
    byte resBytes[] = new byte[rBytes.length];
    resBytes = result.toByteArray();
    for (int i = 0; i < resBytes.length; i++) {
        assertTrue(resBytes[i] == rBytes[i]);
    }
    assertEquals("incorrect sign", -1, result.signum());
}

95. BigIntegerAddTest#testCase10()

Project: j2objc
Source File: BigIntegerAddTest.java
View license
/**
     * Add two negative numbers of different length.
     * The second is longer.
     */
public void testCase10() {
    byte aBytes[] = { 10, 20, 30, 40, 50, 60, 70, 10, 20, 30 };
    byte bBytes[] = { 1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7 };
    int aSign = -1;
    int bSign = -1;
    byte rBytes[] = { -2, -3, -4, -5, -16, -27, -38, -42, -53, -64, -75, -16, -27, -37 };
    BigInteger aNumber = new BigInteger(aSign, aBytes);
    BigInteger bNumber = new BigInteger(bSign, bBytes);
    BigInteger result = aNumber.add(bNumber);
    byte resBytes[] = new byte[rBytes.length];
    resBytes = result.toByteArray();
    for (int i = 0; i < resBytes.length; i++) {
        assertTrue(resBytes[i] == rBytes[i]);
    }
    assertEquals("incorrect sign", -1, result.signum());
}

96. BigIntegerAddTest#testCase11()

Project: j2objc
Source File: BigIntegerAddTest.java
View license
/**
     * Add two numbers of different length and sign.
     * The first is positive.
     * The first is longer.
     */
public void testCase11() {
    byte aBytes[] = { 1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7 };
    byte bBytes[] = { 10, 20, 30, 40, 50, 60, 70, 10, 20, 30 };
    int aSign = 1;
    int bSign = -1;
    byte rBytes[] = { 1, 2, 3, 3, -6, -15, -24, -40, -49, -58, -67, -6, -15, -23 };
    BigInteger aNumber = new BigInteger(aSign, aBytes);
    BigInteger bNumber = new BigInteger(bSign, bBytes);
    BigInteger result = aNumber.add(bNumber);
    byte resBytes[] = new byte[rBytes.length];
    resBytes = result.toByteArray();
    for (int i = 0; i < resBytes.length; i++) {
        assertTrue(resBytes[i] == rBytes[i]);
    }
    assertEquals("incorrect sign", 1, result.signum());
}

97. BigIntegerAddTest#testCase12()

Project: j2objc
Source File: BigIntegerAddTest.java
View license
/**
     * Add two numbers of different length and sign.
     * The first is positive.
     * The second is longer.
     */
public void testCase12() {
    byte aBytes[] = { 10, 20, 30, 40, 50, 60, 70, 10, 20, 30 };
    byte bBytes[] = { 1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7 };
    int aSign = 1;
    int bSign = -1;
    byte rBytes[] = { -2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23 };
    BigInteger aNumber = new BigInteger(aSign, aBytes);
    BigInteger bNumber = new BigInteger(bSign, bBytes);
    BigInteger result = aNumber.add(bNumber);
    byte resBytes[] = new byte[rBytes.length];
    resBytes = result.toByteArray();
    for (int i = 0; i < resBytes.length; i++) {
        assertTrue(resBytes[i] == rBytes[i]);
    }
    assertEquals("incorrect sign", -1, result.signum());
}

98. BigIntegerAddTest#testCase13()

Project: j2objc
Source File: BigIntegerAddTest.java
View license
/**
     * Add two numbers of different length and sign.
     * The first is negative.
     * The first is longer.
     */
public void testCase13() {
    byte aBytes[] = { 1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7 };
    byte bBytes[] = { 10, 20, 30, 40, 50, 60, 70, 10, 20, 30 };
    int aSign = -1;
    int bSign = 1;
    byte rBytes[] = { -2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23 };
    BigInteger aNumber = new BigInteger(aSign, aBytes);
    BigInteger bNumber = new BigInteger(bSign, bBytes);
    BigInteger result = aNumber.add(bNumber);
    byte resBytes[] = new byte[rBytes.length];
    resBytes = result.toByteArray();
    for (int i = 0; i < resBytes.length; i++) {
        assertTrue(resBytes[i] == rBytes[i]);
    }
    assertEquals("incorrect sign", -1, result.signum());
}

99. BigIntegerAddTest#testCase14()

Project: j2objc
Source File: BigIntegerAddTest.java
View license
/**
     * Add two numbers of different length and sign.
     * The first is negative.
     * The second is longer.
     */
public void testCase14() {
    byte aBytes[] = { 10, 20, 30, 40, 50, 60, 70, 10, 20, 30 };
    byte bBytes[] = { 1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7 };
    int aSign = -1;
    int bSign = 1;
    byte rBytes[] = { 1, 2, 3, 3, -6, -15, -24, -40, -49, -58, -67, -6, -15, -23 };
    BigInteger aNumber = new BigInteger(aSign, aBytes);
    BigInteger bNumber = new BigInteger(bSign, bBytes);
    BigInteger result = aNumber.add(bNumber);
    byte resBytes[] = new byte[rBytes.length];
    resBytes = result.toByteArray();
    for (int i = 0; i < resBytes.length; i++) {
        assertTrue(resBytes[i] == rBytes[i]);
    }
    assertEquals("incorrect sign", 1, result.signum());
}

100. BigIntegerAddTest#testCase15()

Project: j2objc
Source File: BigIntegerAddTest.java
View license
/**
     * Add two equal numbers of different signs
     */
public void testCase15() {
    byte aBytes[] = { 1, 2, 3, 4, 5, 6, 7 };
    byte bBytes[] = { 1, 2, 3, 4, 5, 6, 7 };
    byte rBytes[] = { 0 };
    int aSign = -1;
    int bSign = 1;
    BigInteger aNumber = new BigInteger(aSign, aBytes);
    BigInteger bNumber = new BigInteger(bSign, bBytes);
    BigInteger result = aNumber.add(bNumber);
    byte resBytes[] = new byte[rBytes.length];
    for (int i = 0; i < resBytes.length; i++) {
        assertTrue(resBytes[i] == rBytes[i]);
    }
    assertEquals("incorrect sign", 0, result.signum());
}