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

The following examples show how to use java.math.BigInteger#subtract() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BigIntegerSubtractTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Subtract two negative numbers of the same length.
 * The first is greater in absolute value.
 */
public void testCase5() {
    byte aBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30};
    byte bBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3};
    int aSign = -1;
    int bSign = -1;        
    byte rBytes[] = {-10, -19, -28, -37, -46, -55, -64, -10, -19, -27};
    BigInteger aNumber = new BigInteger(aSign, aBytes);
    BigInteger bNumber = new BigInteger(bSign, bBytes);
    BigInteger result = aNumber.subtract(bNumber);
    byte resBytes[] = new byte[rBytes.length];
    resBytes = result.toByteArray();
    for(int i = 0; i < resBytes.length; i++) {
        assertTrue(resBytes[i] == rBytes[i]);
    }
    assertEquals(-1, result.signum());
}
 
Example 2
Source File: SM2Algorithm.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
/**
 * SM2私钥签名
 *
 * @param hash 32字节hash
 * @param privateKeyS
 * @return
 * @date 2015年12月3日
 * @author fisco-bcos
 */
private static BigInteger[] SignSm3(byte[] hash, BigInteger privateKeyS) {
    byte[] hashData = ByteUtils.copyBytes(hash);
    BigInteger e = new BigInteger(1, hashData);
    BigInteger k = null;
    ECPoint kp = null;
    BigInteger r = null;
    BigInteger s = null;
    BigInteger userD = privateKeyS;
    do {
        do {
            k = createRandom();
            kp = g256.multiply(k);
            ECPoint ecPoint = kp.normalize();
            r = e.add(ecPoint.getAffineXCoord().toBigInteger());
            r = r.mod(n);
        } while (r.equals(BigInteger.ZERO) || r.add(k).equals(n));
        BigInteger da_1 = userD.add(BigInteger.ONE).modInverse(n);
        s = r.multiply(userD);
        s = k.subtract(s);
        s = s.multiply(da_1);
        s = s.mod(n);
    } while (s.equals(BigInteger.ZERO));
    BigInteger[] retRS = {r, s};
    return retRS;
}
 
Example 3
Source File: Gcd.java    From symja_android_library with GNU General Public License v3.0 6 votes vote down vote up
public BigInteger gcd_euclid_withoutDivision(BigInteger m, BigInteger n) {
	m = m.abs();
	n = n.abs();
	int mCmp1 = m.compareTo(I_1);
	int nCmp1 = n.compareTo(I_1);
	if (mCmp1>0 && nCmp1>0) {
		int cmp = m.compareTo(n);
		while (cmp != 0) {
			//LOG.debug("m = " + m + ", n = " + n + ", cmp = " + cmp);
			if (cmp > 0) {
				m = m.subtract(n);
			} else {
				n = n.subtract(m);
			}
			cmp = m.compareTo(n);
		}
		return m;
	}
	if (mCmp1<0) return n;
	if (nCmp1<0) return m;
	// else one argument is 1
	return I_1;
}
 
Example 4
Source File: Combination.java    From raistlic-lib-commons-core with Apache License 2.0 6 votes vote down vote up
@Override
public void fetchCombination(Object[] source, Object[] target, BigInteger ordinal) {
  
  // no parameter validation because this is only called in the package.
  
  for(int i=0, si=0; i<target.length; i++, si++) {

    if( ordinal.compareTo(BigInteger.ZERO) > 0 ) {

      BigInteger cLeft = getCombinationCount(source.length - si - 1, target.length - i - 1);
      while( ordinal.compareTo(cLeft) >= 0 ) {
        si++;
        ordinal = ordinal.subtract(cLeft);
        if( ordinal.compareTo(BigInteger.ZERO) == 0 ) {
          break;
        }
        cLeft = getCombinationCount(source.length - si - 1, target.length - i - 1);
      }
    }
    target[i] = source[si];
  }
}
 
Example 5
Source File: BigIntAbstractOperations.java    From es6draft with MIT License 5 votes vote down vote up
/**
 * ToBigInt64 ( argument )
 * 
 * @param n
 *            the argument value
 * @return the {@code long} result value
 */
private static BigInteger ToBigInt64Raw(BigInteger n) {
    /* step 1 (not applicable) */
    /* step 2 */
    BigInteger int64bit = n.mod(TWO_64);
    /* step 3 */
    return int64bit.compareTo(TWO_63) >= 0 ? int64bit.subtract(TWO_64) : int64bit;
}
 
Example 6
Source File: UpcKeygen.java    From upcKeygen with GNU General Public License v2.0 5 votes vote down vote up
public void doComputeKeys() throws UnsupportedEncodingException {
    final byte[] ssidBytes = (getSsidName()+"\0").getBytes("US-ASCII");
    if (isUbee == 0){
        Log.d(TAG, "Starting a new task for ssid (UPC): " + getSsidName());
        //upcUbeeSsidFind(ssidBytes);
        upcNative(ssidBytes, getMode());

    } else {
        Log.d(TAG, "Starting a new task for mac (Ubee): " + getMacAddress());

        // Ubee extension first, better matching.
        final BigInteger macInt = new BigInteger(getMacAddress(), 16);
        final BigInteger macStart = macInt.subtract(BigInteger.valueOf(6));
        for(int i=0; i<12; i++){
            final BigInteger curMac = macStart.add(BigInteger.valueOf(i));
            final String curSsid = upcUbeeSsid(curMac.toByteArray());
            final String curPass = upcUbeePass(curMac.toByteArray());

            WiFiKey wiFiKey = new WiFiKey(curPass, "", getMode(), computedKeys.size());
            wiFiKey.setSsid(curSsid);

            computedKeys.add(wiFiKey);
            if (monitor != null){
                monitor.onKeyComputed();
            }
        }
    }
}
 
Example 7
Source File: Account.java    From ethereumj with MIT License 5 votes vote down vote up
public BigInteger getBalance() {

        AccountState accountState =
                WorldManager.getInstance().getRepository().getAccountState(this.address);

        BigInteger balance = BigInteger.ZERO;

        if (accountState != null)
            balance = accountState.getBalance();

        synchronized (pendingTransactions){
            if (!pendingTransactions.isEmpty()){

                for (Transaction tx : pendingTransactions){
                    if (Arrays.equals(this.address, tx.getSender())){
                        balance = balance.subtract(new BigInteger(1, tx.getValue()));
                    }

                    if (Arrays.equals(this.address, tx.getReceiveAddress())){
                        balance = balance.add(new BigInteger(1, tx.getValue()));
                    }
                }
                // todo: calculate the fee for pending
            }
        }
        return balance;
    }
 
Example 8
Source File: BigIntEuclidean.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
/**
 * Runs the EEA on two <code>BigInteger</code>s<br>
 * Implemented from pseudocode on <a href="http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm">Wikipedia</a>.
 *
 * @param a
 * @param b
 * @return a <code>BigIntEuclidean</code> object that contains the result in the variables <code>x</code>, <code>y</code>, and <code>gcd</code>
 */
public static BigIntEuclidean calculate(BigInteger a, BigInteger b)
{
    BigInteger x = BigInteger.ZERO;
    BigInteger lastx = BigInteger.ONE;
    BigInteger y = BigInteger.ONE;
    BigInteger lasty = BigInteger.ZERO;
    while (!b.equals(BigInteger.ZERO))
    {
        BigInteger[] quotientAndRemainder = a.divideAndRemainder(b);
        BigInteger quotient = quotientAndRemainder[0];

        BigInteger temp = a;
        a = b;
        b = quotientAndRemainder[1];

        temp = x;
        x = lastx.subtract(quotient.multiply(x));
        lastx = temp;

        temp = y;
        y = lasty.subtract(quotient.multiply(y));
        lasty = temp;
    }

    BigIntEuclidean result = new BigIntEuclidean();
    result.x = lastx;
    result.y = lasty;
    result.gcd = a;
    return result;
}
 
Example 9
Source File: Simulation.java    From chvote-protocol-poc with GNU Affero General Public License v3.0 5 votes vote down vote up
private EncryptionGroup createEncryptionGroup(BigInteger p) {
    log.info("creating encryption group");
    EncryptionGroup encryptionGroup = null;

    while (encryptionGroup == null) {
        if (!p.isProbablePrime(100)) {
            log.info("p is not prime...");
            continue;
        }

        BigInteger pMinusOne = p.subtract(ONE);
        BigInteger q = pMinusOne.shiftRight(1);
        if (!q.isProbablePrime(100)) {
            log.info("q is not prime...");
        }

        BigInteger g = getGenerator(q, p, pMinusOne);

        BigInteger h = randomGenerator.randomInGq(new EncryptionGroup(p, q, g, TWO));

        try {
            encryptionGroup = new EncryptionGroup(p, q, g, h);
        } catch (IllegalArgumentException e) {
            log.warn("Encryption group creation failed", e);
            encryptionGroup = null;
        }
    }
    log.info("encryption group created: " + encryptionGroup);
    return encryptionGroup;
}
 
Example 10
Source File: ECUtil.java    From ECTester with MIT License 5 votes vote down vote up
public static EC_Params fullRandomPoint(EC_Curve curve) {
    EllipticCurve ecCurve = curve.toCurve();

    BigInteger p;
    if (ecCurve.getField() instanceof ECFieldFp) {
        ECFieldFp fp = (ECFieldFp) ecCurve.getField();
        p = fp.getP();
        if (!p.isProbablePrime(20)) {
            return null;
        }
    } else {
        //TODO
        return null;
    }
    BigInteger x;
    BigInteger rhs;
    do {
        x = new BigInteger(ecCurve.getField().getFieldSize(), rand).mod(p);
        rhs = computeRHS(x, ecCurve.getA(), ecCurve.getB(), p);
    } while (!isResidue(rhs, p));
    BigInteger y = modSqrt(rhs, p);
    if (rand.nextBoolean()) {
        y = p.subtract(y);
    }

    byte[] xArr = toByteArray(x, ecCurve.getField().getFieldSize());
    byte[] yArr = toByteArray(y, ecCurve.getField().getFieldSize());
    return new EC_Params(EC_Consts.PARAMETER_W, new byte[][]{xArr, yArr});
}
 
Example 11
Source File: OldBigIntegerTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
static void largePrimesProduct(BigInteger a, BigInteger b, String c) {
        BigInteger wp = a.multiply(b);
        assertFalse("isProbablePrime failed for product of two large primes" +
                        a + " * " + b + " = " + c,
                wp.isProbablePrime(80) );
        BigInteger wpMinusOne = wp.subtract(BigInteger.ONE);
        BigInteger next = wpMinusOne.nextProbablePrime();
//        System.out.println(c);
//        System.out.println(next);
        assertTrue("nextProbablePrime returns wrong number: " + next +
                        "instead of expected: " + c,
                next.toString().equals(c) );
    }
 
Example 12
Source File: ObjectIdentifier.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Private helper method for serialization. To be compatible with old
 * versions of JDK.
 * @return components in an int array, if all the components are less than
 *         Integer.MAX_VALUE. Otherwise, null.
 */
private int[] toIntArray() {
    int length = encoding.length;
    int[] result = new int[20];
    int which = 0;
    int fromPos = 0;
    for (int i = 0; i < length; i++) {
        if ((encoding[i] & 0x80) == 0) {
            // one section [fromPos..i]
            if (i - fromPos + 1 > 4) {
                BigInteger big = new BigInteger(pack(encoding, fromPos, i-fromPos+1, 7, 8));
                if (fromPos == 0) {
                    result[which++] = 2;
                    BigInteger second = big.subtract(BigInteger.valueOf(80));
                    if (second.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) == 1) {
                        return null;
                    } else {
                        result[which++] = second.intValue();
                    }
                } else {
                    if (big.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) == 1) {
                        return null;
                    } else {
                        result[which++] = big.intValue();
                    }
                }
            } else {
                int retval = 0;
                for (int j = fromPos; j <= i; j++) {
                    retval <<= 7;
                    byte tmp = encoding[j];
                    retval |= (tmp & 0x07f);
                }
                if (fromPos == 0) {
                    if (retval < 80) {
                        result[which++] = retval / 40;
                        result[which++] = retval % 40;
                    } else {
                        result[which++] = 2;
                        result[which++] = retval - 80;
                    }
                } else {
                    result[which++] = retval;
                }
            }
            fromPos = i+1;
        }
        if (which >= result.length) {
            result = Arrays.copyOf(result, which + 10);
        }
    }
    return Arrays.copyOf(result, which);
}
 
Example 13
Source File: RSAKeyPairGenerator.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
public KeyPair generateKeyPair() {
    // accommodate odd key sizes in case anybody wants to use them
    int lp = (keySize + 1) >> 1;
    int lq = keySize - lp;
    if (random == null) {
        random = JCAUtil.getSecureRandom();
    }
    BigInteger e = publicExponent;
    while (true) {
        // generate two random primes of size lp/lq
        BigInteger p = BigInteger.probablePrime(lp, random);
        BigInteger q, n;
        do {
            q = BigInteger.probablePrime(lq, random);
            // convention is for p > q
            if (p.compareTo(q) < 0) {
                BigInteger tmp = p;
                p = q;
                q = tmp;
            }
            // modulus n = p * q
            n = p.multiply(q);
            // even with correctly sized p and q, there is a chance that
            // n will be one bit short. re-generate the smaller prime if so
        } while (n.bitLength() < keySize);

        // phi = (p - 1) * (q - 1) must be relative prime to e
        // otherwise RSA just won't work ;-)
        BigInteger p1 = p.subtract(BigInteger.ONE);
        BigInteger q1 = q.subtract(BigInteger.ONE);
        BigInteger phi = p1.multiply(q1);
        // generate new p and q until they work. typically
        // the first try will succeed when using F4
        if (e.gcd(phi).equals(BigInteger.ONE) == false) {
            continue;
        }

        // private exponent d is the inverse of e mod phi
        BigInteger d = e.modInverse(phi);

        // 1st prime exponent pe = d mod (p - 1)
        BigInteger pe = d.mod(p1);
        // 2nd prime exponent qe = d mod (q - 1)
        BigInteger qe = d.mod(q1);

        // crt coefficient coeff is the inverse of q mod p
        BigInteger coeff = q.modInverse(p);

        try {
            PublicKey publicKey = new RSAPublicKeyImpl(n, e);
            PrivateKey privateKey =
                    new RSAPrivateCrtKeyImpl(n, e, d, p, q, pe, qe, coeff);
            return new KeyPair(publicKey, privateKey);
        } catch (InvalidKeyException exc) {
            // invalid key exception only thrown for keys < 512 bit,
            // will not happen here
            throw new RuntimeException(exc);
        }
    }
}
 
Example 14
Source File: TransactionServiceImpl.java    From nuls-v2 with MIT License 4 votes vote down vote up
/**
 * 组装coinData数据
 * assembly coinData
 *
 * @param listFrom
 * @param listTo
 * @param txSize
 * @return
 * @throws NulsException
 */
private CoinData getCoinData(Chain chain, List<CoinFrom> listFrom, List<CoinTo> listTo, int txSize) throws NulsException {
    //总来源费用
    BigInteger feeTotalFrom = BigInteger.ZERO;
    for (CoinFrom coinFrom : listFrom) {
        txSize += coinFrom.size();
        if (TxUtil.isMainAsset(chain, coinFrom.getAssetsChainId(), coinFrom.getAssetsId())) {
            feeTotalFrom = feeTotalFrom.add(coinFrom.getAmount());
        }
    }
    //总转出费用
    BigInteger feeTotalTo = BigInteger.ZERO;
    for (CoinTo coinTo : listTo) {
        txSize += coinTo.size();
        if (TxUtil.isMainAsset(chain, coinTo.getAssetsChainId(), coinTo.getAssetsId())) {
            feeTotalTo = feeTotalTo.add(coinTo.getAmount());
        }
    }
    //本交易预计收取的手续费
    BigInteger targetFee = TransactionFeeCalculator.getNormalTxFee(txSize);
    //实际收取的手续费, 可能自己已经组装完成
    BigInteger actualFee = feeTotalFrom.subtract(feeTotalTo);
    if (BigIntegerUtils.isLessThan(actualFee, BigInteger.ZERO)) {
        chain.getLogger().error("insufficient fee");
        //所有from中账户的当前链主资产余额总和小于to的总和,不够支付手续费
        throw new NulsException(AccountErrorCode.INSUFFICIENT_FEE);
    } else if (BigIntegerUtils.isLessThan(actualFee, targetFee)) {
        //只从资产为当前链主资产的coinfrom中收取手续费
        actualFee = getFeeDirect(chain, listFrom, targetFee, actualFee);
        if (BigIntegerUtils.isLessThan(actualFee, targetFee)) {
            //如果没收到足够的手续费,则从CoinFrom中资产不是当前链主资产的coin账户中查找当前链主资产余额,并组装新的coinfrom来收取手续费
            if (!getFeeIndirect(chain, listFrom, txSize, targetFee, actualFee)) {
                chain.getLogger().error("insufficient fee");
                //所有from中账户的当前链主资产余额总和都不够支付手续费
                throw new NulsException(AccountErrorCode.INSUFFICIENT_FEE);
            }
        }
    }
    CoinData coinData = new CoinData();
    coinData.setFrom(listFrom);
    coinData.setTo(listTo);
    return coinData;
}
 
Example 15
Source File: BigIntegerMutatorTest.java    From pitest with Apache License 2.0 4 votes vote down vote up
@Override
BigInteger apply(BigInteger left, BigInteger right) {
  return left.subtract(right);
}
 
Example 16
Source File: TriadicCensus.java    From flink with Apache License 2.0 4 votes vote down vote up
@Override
public Result getResult() {
	// vertex metrics
	BigInteger bigVertexCount = BigInteger.valueOf(vertexMetrics.getResult().getNumberOfVertices());
	BigInteger bigEdgeCount = BigInteger.valueOf(vertexMetrics.getResult().getNumberOfEdges());
	BigInteger bigTripletCount = BigInteger.valueOf(vertexMetrics.getResult().getNumberOfTriplets());

	// triangle count
	BigInteger bigTriangleCount = BigInteger.valueOf(triangleCount.getResult());

	BigInteger one = BigInteger.ONE;
	BigInteger two = BigInteger.valueOf(2);
	BigInteger three = BigInteger.valueOf(3);
	BigInteger six = BigInteger.valueOf(6);

	// counts as ordered in TriadicCensus.Result
	BigInteger[] counts = new BigInteger[4];

	// triads with three connecting edges = closed triplet = triangle
	counts[3] = bigTriangleCount;

	// triads with two connecting edges = open triplet;
	// deduct each triplet having been counted three times per triangle
	counts[2] = bigTripletCount.subtract(bigTriangleCount.multiply(three));

	// triads with one connecting edge; each edge pairs with `vertex count - 2` vertices
	// then deduct twice for each open triplet and three times for each triangle
	counts[1] = bigEdgeCount
		.multiply(bigVertexCount.subtract(two))
		.subtract(counts[2].multiply(two))
		.subtract(counts[3].multiply(three));

	// triads with zero connecting edges;
	// (vertex count choose 3) minus earlier counts
	counts[0] = bigVertexCount
		.multiply(bigVertexCount.subtract(one))
		.multiply(bigVertexCount.subtract(two))
		.divide(six)
		.subtract(counts[1])
		.subtract(counts[2])
		.subtract(counts[3]);

	return new Result(counts);
}
 
Example 17
Source File: SupportedDHKeys.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
private static void checkKeyPair(KeyPair kp, int pSize,
            Provider provider) throws Exception {

    DHPrivateKey privateKey = (DHPrivateKey)kp.getPrivate();
    BigInteger p = privateKey.getParams().getP();
    if (p.bitLength() != pSize) {
        throw new Exception(
            "Invalid modulus size: " + p.bitLength() + "/" + pSize);
    }

    // System.out.println("P(" + pSize + "): " + p.toString());
    if (!p.isProbablePrime(128)) {
        throw new Exception("Good luck, the modulus is composite!");
    }

    DHPublicKey publicKey = (DHPublicKey)kp.getPublic();
    p = publicKey.getParams().getP();
    if (p.bitLength() != pSize) {
        throw new Exception(
            "Invalid modulus size: " + p.bitLength() + "/" + pSize);
    }

    BigInteger leftOpen = BigInteger.ONE;
    BigInteger rightOpen = p.subtract(BigInteger.ONE);

    // ignore the private key range checking on Solaris at present
    if (provider.getName().equals("SunPKCS11-Solaris") &&
            !System.getProperty("os.name").equals("SunOS")) {
        BigInteger x = privateKey.getX();
        if ((x.compareTo(leftOpen) <= 0) ||
                (x.compareTo(rightOpen) >= 0)) {
            throw new Exception(
                "X outside range [2, p - 2]:  x: " + x + " p: " + p);
        }
    }

    BigInteger y = publicKey.getY();
    if ((y.compareTo(leftOpen) <= 0) ||
            (y.compareTo(rightOpen) >= 0)) {
        throw new Exception(
            "Y outside range [2, p - 2]:  y: " + y + " p: " + p);
    }
}
 
Example 18
Source File: Bytes.java    From hbase with Apache License 2.0 4 votes vote down vote up
/**
 * Iterate over keys within the passed range.
 */
public static Iterable<byte[]> iterateOnSplits(
    final byte[] a, final byte[]b, boolean inclusive, final int num)
{
  byte [] aPadded;
  byte [] bPadded;
  if (a.length < b.length) {
    aPadded = padTail(a, b.length - a.length);
    bPadded = b;
  } else if (b.length < a.length) {
    aPadded = a;
    bPadded = padTail(b, a.length - b.length);
  } else {
    aPadded = a;
    bPadded = b;
  }
  if (compareTo(aPadded,bPadded) >= 0) {
    throw new IllegalArgumentException("b <= a");
  }
  if (num <= 0) {
    throw new IllegalArgumentException("num cannot be <= 0");
  }
  byte [] prependHeader = {1, 0};
  final BigInteger startBI = new BigInteger(add(prependHeader, aPadded));
  final BigInteger stopBI = new BigInteger(add(prependHeader, bPadded));
  BigInteger diffBI = stopBI.subtract(startBI);
  if (inclusive) {
    diffBI = diffBI.add(BigInteger.ONE);
  }
  final BigInteger splitsBI = BigInteger.valueOf(num + 1);
  //when diffBI < splitBI, use an additional byte to increase diffBI
  if(diffBI.compareTo(splitsBI) < 0) {
    byte[] aPaddedAdditional = new byte[aPadded.length+1];
    byte[] bPaddedAdditional = new byte[bPadded.length+1];
    for (int i = 0; i < aPadded.length; i++){
      aPaddedAdditional[i] = aPadded[i];
    }
    for (int j = 0; j < bPadded.length; j++){
      bPaddedAdditional[j] = bPadded[j];
    }
    aPaddedAdditional[aPadded.length] = 0;
    bPaddedAdditional[bPadded.length] = 0;
    return iterateOnSplits(aPaddedAdditional, bPaddedAdditional, inclusive,  num);
  }
  final BigInteger intervalBI;
  try {
    intervalBI = diffBI.divide(splitsBI);
  } catch(Exception e) {
    LOG.error("Exception caught during division", e);
    return null;
  }

  final Iterator<byte[]> iterator = new Iterator<byte[]>() {
    private int i = -1;

    @Override
    public boolean hasNext() {
      return i < num+1;
    }

    @Override
    public byte[] next() {
      i++;
      if (i == 0) return a;
      if (i == num + 1) return b;

      BigInteger curBI = startBI.add(intervalBI.multiply(BigInteger.valueOf(i)));
      byte [] padded = curBI.toByteArray();
      if (padded[1] == 0)
        padded = tail(padded, padded.length - 2);
      else
        padded = tail(padded, padded.length - 1);
      return padded;
    }

    @Override
    public void remove() {
      throw new UnsupportedOperationException();
    }

  };

  return new Iterable<byte[]>() {
    @Override
    public Iterator<byte[]> iterator() {
      return iterator;
    }
  };
}
 
Example 19
Source File: RSACore.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * RSA private key operations with CRT. Algorithm and variable naming
 * are taken from PKCS#1 v2.1, section 5.1.2.
 */
private static byte[] crtCrypt(byte[] msg, RSAPrivateCrtKey key,
        boolean verify) throws BadPaddingException {
    BigInteger n = key.getModulus();
    BigInteger c0 = parseMsg(msg, n);
    BigInteger c = c0;
    BigInteger p = key.getPrimeP();
    BigInteger q = key.getPrimeQ();
    BigInteger dP = key.getPrimeExponentP();
    BigInteger dQ = key.getPrimeExponentQ();
    BigInteger qInv = key.getCrtCoefficient();
    BigInteger e = key.getPublicExponent();
    BigInteger d = key.getPrivateExponent();

    BlindingRandomPair brp;
    if (ENABLE_BLINDING) {
        brp = getBlindingRandomPair(e, d, n);
        c = c.multiply(brp.u).mod(n);
    }

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

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

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

    if (ENABLE_BLINDING) {
        m = m.multiply(brp.v).mod(n);
    }
    if (verify && !c0.equals(m.modPow(e, n))) {
        throw new BadPaddingException("RSA private key operation failed");
    }

    return toByteArray(m, getByteLength(n));
}
 
Example 20
Source File: ByteKeyRange.java    From beam with Apache License 2.0 4 votes vote down vote up
/**
 * Returns the fraction of this range {@code [startKey, endKey)} that is in the interval {@code
 * [startKey, key)}.
 *
 * @throws IllegalArgumentException if {@code key} does not fall within this range
 * @see ByteKeyRange the ByteKeyRange class Javadoc for more information about fraction semantics.
 */
public double estimateFractionForKey(ByteKey key) {
  checkNotNull(key, "key");
  checkArgument(!key.isEmpty(), "Cannot compute fraction for an empty key");
  checkArgument(
      key.compareTo(startKey) >= 0, "Expected key %s >= range start key %s", key, startKey);

  if (key.equals(endKey)) {
    return 1.0;
  }
  checkArgument(containsKey(key), "Cannot compute fraction for %s outside this %s", key, this);

  byte[] startBytes = startKey.getBytes();
  byte[] endBytes = endKey.getBytes();
  byte[] keyBytes = key.getBytes();
  // If the endKey is unspecified, add a leading 1 byte to it and a leading 0 byte to all other
  // keys, to get a concrete least upper bound for the desired range.
  if (endKey.isEmpty()) {
    startBytes = addHeadByte(startBytes, (byte) 0);
    endBytes = addHeadByte(endBytes, (byte) 1);
    keyBytes = addHeadByte(keyBytes, (byte) 0);
  }

  // Pad to the longest of all 3 keys.
  int paddedKeyLength = Math.max(Math.max(startBytes.length, endBytes.length), keyBytes.length);
  BigInteger rangeStartInt = paddedPositiveInt(startBytes, paddedKeyLength);
  BigInteger rangeEndInt = paddedPositiveInt(endBytes, paddedKeyLength);
  BigInteger keyInt = paddedPositiveInt(keyBytes, paddedKeyLength);

  // Keys are equal subject to padding by 0.
  BigInteger range = rangeEndInt.subtract(rangeStartInt);
  if (range.equals(BigInteger.ZERO)) {
    LOG.warn(
        "Using 0.0 as the default fraction for this near-empty range {} where start and end keys"
            + " differ only by trailing zeros.",
        this);
    return 0.0;
  }

  // Compute the progress (key-start)/(end-start) scaling by 2^64, dividing (which rounds),
  // and then scaling down after the division. This gives ample precision when converted to
  // double.
  BigInteger progressScaled = keyInt.subtract(rangeStartInt).shiftLeft(64);
  return progressScaled.divide(range).doubleValue() / Math.pow(2, 64);
}