Example usage for java.math BigInteger subtract

List of usage examples for java.math BigInteger subtract

Introduction

In this page you can find the example usage for java.math BigInteger subtract.

Prototype

public BigInteger subtract(BigInteger val) 

Source Link

Document

Returns a BigInteger whose value is (this - val) .

Usage

From source file:libra.preprocess.common.kmerhistogram.KmerRangePartitioner.java

public KmerRangePartition[] getHistogramPartitions(KmerHistogramRecord[] records, long samples) {
    KmerRangePartition[] partitions = new KmerRangePartition[this.numPartitions];

    // calc 4^kmerSize
    String As = "";
    String Ts = "";
    for (int i = 0; i < this.kmerSize; i++) {
        As += "A";
        Ts += "T";
    }// w  w  w .  ja  va  2 s  . c o  m

    long partitionWidth = samples / this.numPartitions;
    long partitionWidthRemain = partitionWidth;
    int partitionIdx = 0;
    int recordIdx = 0;
    long curRecordRemain = records[0].getFrequency();
    BigInteger nextPartitionBegin = BigInteger.ZERO;
    while (partitionIdx < this.numPartitions) {
        long diff = partitionWidthRemain - curRecordRemain;
        if (diff > 0) {
            partitionWidthRemain -= curRecordRemain;
            recordIdx++;
            if (recordIdx < records.length) {
                curRecordRemain = records[recordIdx].getFrequency();
            } else {
                break;
            }
        } else if (diff == 0) {
            BigInteger partitionBegin = nextPartitionBegin;
            BigInteger partitionEnd = null;
            if (partitionIdx == this.numPartitions - 1) {
                partitionEnd = SequenceHelper.convertToBigInteger(Ts);
            } else {
                partitionEnd = SequenceHelper
                        .convertToBigInteger((records[recordIdx].getKmer() + Ts).substring(0, this.kmerSize));
            }
            BigInteger partitionSize = partitionEnd.subtract(partitionBegin);
            partitions[partitionIdx] = new KmerRangePartition(this.kmerSize, this.numPartitions, partitionIdx,
                    partitionSize, partitionBegin, partitionEnd);

            nextPartitionBegin = partitionEnd.add(BigInteger.ONE);
            partitionIdx++;
            recordIdx++;
            if (recordIdx < records.length) {
                curRecordRemain = records[recordIdx].getFrequency();
            } else {
                break;
            }
            partitionWidthRemain = partitionWidth;
        } else {
            // in between
            BigInteger partitionBegin = nextPartitionBegin;
            BigInteger partitionEnd = null;
            if (partitionIdx == this.numPartitions - 1) {
                partitionEnd = SequenceHelper.convertToBigInteger(Ts);
            } else {
                BigInteger recordBegin = SequenceHelper
                        .convertToBigInteger((records[recordIdx].getKmer() + As).substring(0, this.kmerSize));
                BigInteger recordEnd = SequenceHelper
                        .convertToBigInteger((records[recordIdx].getKmer() + Ts).substring(0, this.kmerSize));
                BigInteger recordWidth = recordEnd.subtract(recordBegin);
                BigInteger curWidth = recordWidth.multiply(BigInteger.valueOf(partitionWidthRemain))
                        .divide(BigInteger.valueOf(records[recordIdx].getFrequency()));

                BigInteger bigger = null;
                if (recordBegin.compareTo(partitionBegin) > 0) {
                    bigger = recordBegin;
                } else {
                    bigger = partitionBegin;
                }

                partitionEnd = bigger.add(curWidth);
            }
            BigInteger partitionSize = partitionEnd.subtract(partitionBegin);
            partitions[partitionIdx] = new KmerRangePartition(this.kmerSize, this.numPartitions, partitionIdx,
                    partitionSize, partitionBegin, partitionEnd);

            nextPartitionBegin = partitionEnd.add(BigInteger.ONE);
            partitionIdx++;
            curRecordRemain -= partitionWidthRemain;
            partitionWidthRemain = partitionWidth;
        }
    }

    return partitions;
}

From source file:test.be.fedict.eid.applet.RSATest.java

@Test
public void testManualEncryption() throws Exception {
    while (true) {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA",
                BouncyCastleProvider.PROVIDER_NAME);
        SecureRandom random = new SecureRandom();
        int keySize = 128;
        keyPairGenerator.initialize(new RSAKeyGenParameterSpec(keySize, RSAKeyGenParameterSpec.F0), random);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        PrivateKey privateKey = keyPair.getPrivate();
        PublicKey publicKey = keyPair.getPublic();
        RSAPrivateCrtKey rsaPrivateKey = (RSAPrivateCrtKey) privateKey;
        LOG.debug("private key modulus: " + rsaPrivateKey.getModulus());
        RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
        LOG.debug("public key modulus: " + rsaPublicKey.getModulus());
        LOG.debug("public key exponent: " + rsaPublicKey.getPublicExponent());
        LOG.debug("modulus size: " + rsaPublicKey.getModulus().toByteArray().length);

        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);

        int dataSize = keySize / 8 - 11;
        byte[] data1 = new byte[dataSize];
        for (int i = 0; i < data1.length; i++) {
            data1[i] = 0x00;//from  w  w  w .j a v a2  s  . c o m
        }
        byte[] data2 = new byte[dataSize];
        for (int i = 0; i < data2.length; i++) {
            data2[i] = 0x00;
        }
        data2[data2.length - 1] = 0x07;

        byte[] signatureValue1 = cipher.doFinal(data1);

        LOG.debug("signature size: " + signatureValue1.length);

        cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
        byte[] signatureValue2 = cipher.doFinal(data2);

        BigInteger sigBigInt1 = new BigInteger(signatureValue1);
        BigInteger sigBigInt2 = new BigInteger(signatureValue2);
        BigInteger msgBigInt1 = sigBigInt1.modPow(rsaPublicKey.getPublicExponent(), rsaPublicKey.getModulus());
        BigInteger msgBigInt2 = sigBigInt2.modPow(rsaPublicKey.getPublicExponent(), rsaPublicKey.getModulus());
        LOG.debug("msg big int: " + msgBigInt1);
        byte[] msgBytes1 = msgBigInt1.toByteArray();
        LOG.debug("original message size: " + msgBytes1.length);
        LOG.debug("original message1: " + new String(Hex.encodeHex(msgBytes1)));
        LOG.debug("original message2: " + new String(Hex.encodeHex(msgBigInt2.toByteArray())));

        LOG.debug("msg1 prime: " + msgBigInt1.isProbablePrime(100));
        LOG.debug("msg2 prime: " + msgBigInt2.isProbablePrime(100));

        // BigInteger.pow offers a very naive implementation
        LOG.debug("calculating s1^e...");
        BigInteger s1_e = sigBigInt1.pow(rsaPublicKey.getPublicExponent().intValue());
        LOG.debug("s1^e: " + s1_e);
        LOG.debug("calculating s2^e...");
        BigInteger s2_e = sigBigInt2.pow(rsaPublicKey.getPublicExponent().intValue());
        LOG.debug("s2^e: " + s2_e);

        LOG.debug("calculating GCD...");
        LOG.debug("msg1: " + msgBigInt1);
        LOG.debug("msg2: " + msgBigInt2);
        BigInteger a = s1_e.subtract(msgBigInt1);
        BigInteger b = s2_e.subtract(msgBigInt2);
        LOG.debug("a: " + a);
        LOG.debug("b: " + b);
        BigInteger candidateModulus = a.gcd(b);
        LOG.debug("candidate modulus: " + candidateModulus);
        LOG.debug("candidate modulus size: " + candidateModulus.toByteArray().length);
        BigInteger s_e = s1_e.multiply(s2_e);
        BigInteger m = msgBigInt1.multiply(msgBigInt2);
        while (false == rsaPublicKey.getModulus().equals(candidateModulus)) {
            LOG.error("incorrect candidate modulus");
            LOG.debug("modulus | candidate modulus: "
                    + candidateModulus.remainder(rsaPublicKey.getModulus()).equals(BigInteger.ZERO));
            s_e = s_e.multiply(s1_e);
            m = m.multiply(msgBigInt1);
            BigInteger n1 = s_e.subtract(m).gcd(a);
            BigInteger n2 = s_e.subtract(m).gcd(b);
            candidateModulus = n1.gcd(n2);
            // try / 2
            LOG.debug("new modulus:       " + n1);
            LOG.debug("new modulus:       " + n2);
            LOG.debug("candidate modulus: " + candidateModulus);
            LOG.debug("actual mod:        " + rsaPublicKey.getModulus());
        }
    }
}

From source file:cn.iie.haiep.hbase.value.Bytes.java

/**
 * Iterate over keys within the passed inclusive range.
 *///from   w  w  w. java 2s.  com
public static Iterable<byte[]> iterateOnSplits(final byte[] a, final byte[] b, 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));
    final BigInteger diffBI = stopBI.subtract(startBI);
    final BigInteger splitsBI = BigInteger.valueOf(num + 1);
    if (diffBI.compareTo(splitsBI) < 0) {
        return null;
    }
    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;
        }
    };
}

From source file:libra.preprocess.common.kmerhistogram.KmerRangePartitioner.java

public KmerRangePartition[] getEqualRangePartitions() {
    KmerRangePartition[] partitions = new KmerRangePartition[this.numPartitions];

    // calc 4^kmerSize
    BigInteger kmerend = BigInteger.valueOf(4).pow(this.kmerSize);

    BigInteger slice_width = kmerend.divide(BigInteger.valueOf(this.numPartitions));
    if (kmerend.mod(BigInteger.valueOf(this.numPartitions)).intValue() != 0) {
        slice_width = slice_width.add(BigInteger.ONE);
    }/*from  w  w w  .j ava2  s.co  m*/

    for (int i = 0; i < this.numPartitions; i++) {
        BigInteger slice_begin = slice_width.multiply(BigInteger.valueOf(i));
        if (slice_begin.add(slice_width).compareTo(kmerend) > 0) {
            slice_width = kmerend.subtract(slice_begin);
        }

        BigInteger slice_end = slice_begin.add(slice_width).subtract(BigInteger.ONE);

        KmerRangePartition slice = new KmerRangePartition(this.kmerSize, this.numPartitions, i, slice_width,
                slice_begin, slice_end);
        partitions[i] = slice;
    }

    return partitions;
}

From source file:com.cloud.utils.net.NetUtils.java

public static BigInteger countIp6InRange(final String ip6Range) {
    if (ip6Range == null) {
        return null;
    }/*from ww w  . java  2 s . c om*/
    final String[] ips = ip6Range.split("-");
    final String startIp = ips[0];
    String endIp = ips[0];
    if (ips.length > 1) {
        endIp = ips[1];
    }
    try {
        final BigInteger startInt = convertIPv6AddressToBigInteger(IPv6Address.fromString(startIp));
        final BigInteger endInt = convertIPv6AddressToBigInteger(IPv6Address.fromString(endIp));
        if (endInt != null && startInt != null && startInt.compareTo(endInt) <= 0) {
            return endInt.subtract(startInt).add(BigInteger.ONE);
        }
    } catch (final IllegalArgumentException ex) {
        s_logger.error("Failed to convert a string to an IPv6 address", ex);
    }
    return null;
}

From source file:co.rsk.remasc.Remasc.java

private void payIncludedSiblings(List<Sibling> siblings, BigInteger topReward) {
    long perLateBlockPunishmentDivisor = remascConstants.getLateUncleInclusionPunishmentDivisor();
    for (Sibling sibling : siblings) {
        long processingBlockNumber = executionBlock.getNumber() - remascConstants.getMaturity();
        long numberOfBlocksLate = sibling.getIncludedHeight() - processingBlockNumber - 1L;
        BigInteger lateInclusionPunishment = topReward.multiply(BigInteger.valueOf(numberOfBlocksLate))
                .divide(BigInteger.valueOf(perLateBlockPunishmentDivisor));
        transfer(sibling.getCoinbase(), topReward.subtract(lateInclusionPunishment));
        provider.addToBurnBalance(lateInclusionPunishment);
    }//from   w  w w.  j ava  2 s  .c o  m
}

From source file:co.rsk.remasc.Remasc.java

/**
 * Implements the actual Remasc distribution logic
 */// w  w w.  j  av  a  2s.  c o m
void processMinersFees() {
    if (!(executionTx instanceof RemascTransaction)) {
        //Detect
        // 1) tx to remasc that is not the latest tx in a block
        // 2) invocation to remasc from another contract (ie call opcode)
        throw new RemascInvalidInvocationException("Invoked Remasc outside last tx of the block");
    }
    this.addNewSiblings();

    long blockNbr = executionBlock.getNumber();

    long processingBlockNumber = blockNbr - remascConstants.getMaturity();
    if (processingBlockNumber < 1) {
        logger.debug("First block has not reached maturity yet, current block is {}", blockNbr);
        return;
    }
    BlockHeader processingBlockHeader = blockStore
            .getBlockByHashAndDepth(executionBlock.getParentHash(), remascConstants.getMaturity() - 1)
            .getHeader();
    // Adds current block fees to accumulated rewardBalance
    BigInteger processingBlockReward = BigInteger.valueOf(processingBlockHeader.getPaidFees());
    BigInteger rewardBalance = provider.getRewardBalance();
    rewardBalance = rewardBalance.add(processingBlockReward);
    provider.setRewardBalance(rewardBalance);

    if (processingBlockNumber - remascConstants.getSyntheticSpan() < 0) {
        logger.debug("First block has not reached maturity+syntheticSpan yet, current block is {}",
                executionBlock.getNumber());
        return;
    }

    // Takes from rewardBalance this block's height reward.
    BigInteger fullBlockReward = rewardBalance.divide(BigInteger.valueOf(remascConstants.getSyntheticSpan()));
    rewardBalance = rewardBalance.subtract(fullBlockReward);
    provider.setRewardBalance(rewardBalance);

    // Pay RSK labs cut
    BigInteger payToRskLabs = fullBlockReward.divide(BigInteger.valueOf(remascConstants.getRskLabsDivisor()));
    transfer(remascConstants.getRskLabsAddress(), payToRskLabs);
    fullBlockReward = fullBlockReward.subtract(payToRskLabs);

    List<Sibling> siblings = provider.getSiblings().get(processingBlockNumber);

    if (CollectionUtils.isNotEmpty(siblings)) {
        // Block has siblings, reward distribution is more complex
        boolean previousBrokenSelectionRule = provider.getBrokenSelectionRule();
        this.payWithSiblings(processingBlockHeader, fullBlockReward, siblings, previousBrokenSelectionRule);
        boolean brokenSelectionRule = this.isBrokenSelectionRule(processingBlockHeader, siblings);
        provider.setBrokenSelectionRule(brokenSelectionRule);
    } else {
        if (provider.getBrokenSelectionRule()) {
            // broken selection rule, apply punishment, ie burn part of the reward.
            BigInteger punishment = fullBlockReward
                    .divide(BigInteger.valueOf(remascConstants.getPunishmentDivisor()));
            fullBlockReward = fullBlockReward.subtract(punishment);
            provider.setBurnedBalance(provider.getBurnedBalance().add(punishment));
        }
        transfer(processingBlockHeader.getCoinbase(), fullBlockReward);
        provider.setBrokenSelectionRule(Boolean.FALSE);
    }

    this.removeUsedSiblings(processingBlockHeader);
}

From source file:com.cloud.hypervisor.ovm3.resources.helpers.Ovm3HypervisorSupport.java

/**
 * fillHostInfo: Startup the routing for the host.
 *
 * @param cmd/*  w w w. j  a v  a 2  s  .c  o m*/
 */
public void fillHostInfo(StartupRoutingCommand cmd) {
    try {
        /* get data we need from parts */
        Linux host = new Linux(c);
        if (!host.getOvmVersion().startsWith("3.2.") && !host.getOvmVersion().startsWith("3.3.")) {
            LOGGER.error("Hypervisor not supported: " + host.getOvmVersion());
            throw new CloudRuntimeException("OVM 3.2. or 3.3. are only supported, not " + host.getOvmVersion());
        } else {
            LOGGER.debug("Hypervisor version: " + host.getOvmVersion());
        }
        cmd.setName(host.getHostName());
        cmd.setSpeed(host.getCpuKhz());
        cmd.setCpus(host.getTotalThreads());
        cmd.setCpuSockets(host.getCpuSockets());
        cmd.setMemory(host.getMemory().longValue());
        BigInteger totalmem = BigInteger.valueOf(host.getMemory().longValue());
        BigInteger freemem = BigInteger.valueOf(host.getFreeMemory().longValue());
        cmd.setDom0MinMemory(totalmem.subtract(freemem).longValue());
        // setPoolSync and setCaps.
        cmd.setGuid(config.getCsHostGuid());
        cmd.setDataCenter(config.getAgentZoneId().toString());
        cmd.setPod(config.getAgentPodId().toString());
        /* TODO: cmd.setOwner(host.getManagerUuid()); */
        cmd.setCluster(config.getAgentClusterId().toString());
        cmd.setHypervisorVersion(host.getOvmVersion());
        cmd.setVersion(host.getAgentVersion());
        cmd.setHypervisorType(HypervisorType.Ovm3);
        cmd.setCaps(host.getCapabilities());
        cmd.setPrivateIpAddress(c.getIp());
        cmd.setStorageIpAddress(c.getIp());
        Network net = new Network(c);
        String defaultBridge = net.getBridgeByIp(c.getIp()).getName();
        if (defaultBridge == null) {
            throw new CloudRuntimeException("Unable to obtain valid bridge with " + c.getIp());
        }

        if (config.getAgentPublicNetworkName() == null) {
            config.setAgentPublicNetworkName(defaultBridge);
        }
        if (config.getAgentPrivateNetworkName() == null) {
            config.setAgentPrivateNetworkName(config.getAgentPublicNetworkName());
        }
        if (config.getAgentGuestNetworkName() == null) {
            config.setAgentGuestNetworkName(config.getAgentPublicNetworkName());
        }
        if (config.getAgentStorageNetworkName() == null) {
            config.setAgentStorageNetworkName(config.getAgentPrivateNetworkName());
        }
        Map<String, String> d = cmd.getHostDetails();
        d.put("public.network.device", config.getAgentPublicNetworkName());
        d.put("private.network.device", config.getAgentPrivateNetworkName());
        d.put("guest.network.device", config.getAgentGuestNetworkName());
        d.put("storage.network.device", config.getAgentStorageNetworkName());
        d.put("ismaster", config.getAgentIsMaster().toString());
        d.put("hasmaster", config.getAgentHasMaster().toString());
        cmd.setHostDetails(d);
        LOGGER.debug("Add an Ovm3 host " + config.getAgentHostname() + ":" + cmd.getHostDetails());
    } catch (Ovm3ResourceException e) {
        throw new CloudRuntimeException("Ovm3ResourceException: " + e.getMessage(), e);
    }
}

From source file:com.coinprism.model.APIClient.java

/**
 * Gets the list of recent transactions for a given address.
 *
 * @param address the address for which to query the recent transactions
 * @return a list of transactions/*from  w  w w .j  a v  a 2 s .c om*/
 */
public List<SingleAssetTransaction> getTransactions(String address)
        throws IOException, JSONException, ParseException, APIException {
    String json = executeHttpGet(this.baseUrl + "/v1/addresses/" + address + "/transactions");

    JSONArray transactions = new JSONArray(json);

    ArrayList<SingleAssetTransaction> assetBalances = new ArrayList<SingleAssetTransaction>();

    for (int i = 0; i < transactions.length(); i++) {
        JSONObject transactionObject = (JSONObject) transactions.get(i);
        String transactionId = transactionObject.getString("hash");

        Date date = null;
        if (!transactionObject.isNull("block_time"))
            date = parseDate(transactionObject.getString("block_time"));

        HashMap<String, BigInteger> quantities = new HashMap<String, BigInteger>();
        BigInteger satoshiDelta = BigInteger.ZERO;

        JSONArray inputs = transactionObject.getJSONArray("inputs");
        for (int j = 0; j < inputs.length(); j++) {
            JSONObject input = (JSONObject) inputs.get(j);
            if (isAddress(input, address)) {
                if (!input.isNull("asset_id"))
                    addQuantity(quantities, input.getString("asset_id"),
                            new BigInteger(input.getString("asset_quantity")).negate());

                satoshiDelta = satoshiDelta.subtract(BigInteger.valueOf(input.getLong("value")));
            }
        }

        JSONArray outputs = transactionObject.getJSONArray("outputs");
        for (int j = 0; j < outputs.length(); j++) {
            JSONObject output = (JSONObject) outputs.get(j);
            if (isAddress(output, address)) {
                if (!output.isNull("asset_id"))
                    addQuantity(quantities, output.getString("asset_id"),
                            new BigInteger(output.getString("asset_quantity")));

                satoshiDelta = satoshiDelta.add(BigInteger.valueOf(output.getLong("value")));
            }
        }

        if (!satoshiDelta.equals(BigInteger.ZERO))
            assetBalances.add(new SingleAssetTransaction(transactionId, date, null, satoshiDelta));

        for (String key : quantities.keySet()) {
            assetBalances.add(new SingleAssetTransaction(transactionId, date, getAssetDefinition(key),
                    quantities.get(key)));
        }
    }

    return assetBalances;
}

From source file:com.bonsai.wallet32.HDWallet.java

public AmountAndFee useAll(Wallet wallet, int acctnum, boolean spendUnconfirmed)
        throws InsufficientMoneyException {

    // Create a pretend send request and extract the recommended
    // fee.  Which account are we using for this send?
    HDAccount acct = mAccounts.get(acctnum);

    // Pretend we are sending the bitcoin to ourselves.
    Address dest = acct.nextReceiveAddress();

    SendRequest req = SendRequest.emptyWallet(dest);
    req.coinSelector = acct.coinSelector(spendUnconfirmed);
    req.aesKey = mAesKey;/*ww w.j  av a 2s .c  o  m*/

    // Let the wallet do the heavy lifting ...
    wallet.completeTx(req);

    // It doesn't look like req.fee gets set to the required fee
    // when using emptyWallet.  Figure out the fee ourselves ...
    //
    BigInteger outAmt = req.tx.getValueSentFromMe(wallet);
    BigInteger inAmt = req.tx.getValueSentToMe(wallet);
    BigInteger feeAmt = outAmt.subtract(inAmt);

    return new AmountAndFee(inAmt.longValue(), feeAmt.longValue());
}