Example usage for java.math BigInteger mod

List of usage examples for java.math BigInteger mod

Introduction

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

Prototype

public BigInteger mod(BigInteger m) 

Source Link

Document

Returns a BigInteger whose value is (this mod m ).

Usage

From source file:net.bither.rawprivatekey.RawPrivateKeyBinaryFragment.java

private void handleData() {
    final DialogProgress dp = new DialogProgress(getActivity(), R.string.please_wait);
    dp.show();/*from   ww  w.j  a v  a2  s.  c om*/
    new Thread() {
        @Override
        public void run() {
            final byte[] data = vData.getData();
            if (data == null) {
                return;
            }
            if (!checkValue(data)) {
                ThreadUtil.runOnMainThread(new Runnable() {
                    @Override
                    public void run() {
                        dp.dismiss();
                        DropdownMessage.showDropdownMessage(getActivity(), R.string.raw_private_key_not_safe,
                                new Runnable() {
                                    @Override
                                    public void run() {
                                        vData.setDataSize(16, 16);
                                    }
                                });
                    }
                });
                return;
            }
            BigInteger value = new BigInteger(1, data);
            value = value.mod(ECKey.CURVE.getN());

            ECKey key = new ECKey(value, null, true);
            final String address = Utils.toAddress(key.getPubKeyHash());
            final SecureCharSequence privateKey = new DumpedPrivateKey(key.getPrivKeyBytes(), true)
                    .toSecureCharSequence();
            Utils.wipeBytes(data);
            key.clearPrivateKey();
            ThreadUtil.runOnMainThread(new Runnable() {
                @Override
                public void run() {
                    dp.dismiss();
                    tvPrivateKey.setText(Utils.formatHashFromCharSequence(privateKey, 4, 16));
                    tvAddress.setText(WalletUtils.formatHash(address, 4, 12));
                    llInput.setVisibility(View.GONE);
                    llShow.setVisibility(View.VISIBLE);
                    privateKey.wipe();
                }
            });
        }
    }.start();
}

From source file:net.bither.rawprivatekey.RawPrivateKeyBinaryFragment.java

@Override
public void onPasswordEntered(final SecureCharSequence password) {
    DialogProgress dp = new DialogProgress(getActivity(), R.string.please_wait);
    dp.show();/* w  ww .  j ava  2  s .c o  m*/
    new ThreadNeedService(dp, getActivity()) {
        @Override
        public void runWithService(BlockchainService service) {
            if (service != null) {
                service.stopAndUnregister();
            }
            byte[] data = vData.getData();
            vData.clearData();
            BigInteger value = new BigInteger(1, data);
            value = value.mod(ECKey.CURVE.getN());
            ECKey key = new ECKey(value, null, true);
            key = PrivateKeyUtil.encrypt(key, password);
            Utils.wipeBytes(data);
            password.wipe();
            Address address = new Address(key.toAddress(), key.getPubKey(),
                    PrivateKeyUtil.getEncryptedString(key), false, false);
            key.clearPrivateKey();
            AddressManager.getInstance().addAddress(address);

            if (AppSharedPreference.getInstance().getAppMode() == BitherjSettings.AppMode.COLD) {
                BackupUtil.backupColdKey(false);
            } else {
                BackupUtil.backupHotKey();
            }
            if (service != null) {
                service.startAndRegister();
            }
            ThreadUtil.runOnMainThread(new Runnable() {
                @Override
                public void run() {
                    getActivity().finish();
                    if (AppSharedPreference.getInstance().getAppMode() == BitherjSettings.AppMode.HOT) {
                        Fragment f = BitherApplication.hotActivity.getFragmentAtIndex(1);
                        if (f instanceof HotAddressFragment) {
                            HotAddressFragment hotAddressFragment = (HotAddressFragment) f;
                            hotAddressFragment.refresh();
                        }
                    } else {
                        Fragment f = BitherApplication.coldActivity.getFragmentAtIndex(1);
                        if (f instanceof ColdAddressFragment) {
                            ColdAddressFragment coldAddressFragment = (ColdAddressFragment) f;
                            coldAddressFragment.refresh();
                        }
                    }
                }
            });
        }
    }.start();
}

From source file:net.bither.rawprivatekey.RawPrivateKeyDiceFragment.java

private void handleData() {
    final DialogProgress dp = new DialogProgress(getActivity(), R.string.please_wait);
    dp.show();/*from  w  w  w  .j ava 2 s  .c  om*/
    new Thread() {
        @Override
        public void run() {
            final byte[] data = vData.getData();
            if (data == null) {
                return;
            }
            if (!checkValue(data)) {
                ThreadUtil.runOnMainThread(new Runnable() {
                    @Override
                    public void run() {
                        dp.dismiss();
                        DropdownMessage.showDropdownMessage(getActivity(), R.string.raw_private_key_not_safe,
                                new Runnable() {
                                    @Override
                                    public void run() {
                                        vData.setDataSize(10, 10);
                                    }
                                });
                    }
                });
                return;
            }
            BigInteger value = new BigInteger(1, data);
            value = value.mod(ECKey.CURVE.getN());

            ECKey key = new ECKey(value, null, true);
            final String address = Utils.toAddress(key.getPubKeyHash());
            final SecureCharSequence privateKey = new DumpedPrivateKey(key.getPrivKeyBytes(), true)
                    .toSecureCharSequence();
            Utils.wipeBytes(data);
            key.clearPrivateKey();
            ThreadUtil.runOnMainThread(new Runnable() {
                @Override
                public void run() {
                    dp.dismiss();
                    tvPrivateKey.setText(Utils.formatHashFromCharSequence(privateKey, 4, 16));
                    tvAddress.setText(WalletUtils.formatHash(address, 4, 12));
                    llInput.setVisibility(View.GONE);
                    llShow.setVisibility(View.VISIBLE);
                    privateKey.wipe();
                }
            });
        }
    }.start();
}

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);
    }/*w ww . j  a  va 2  s.c o  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:jef.tools.DateUtils.java

/**
 * ?????//from w  w  w. j a  v a  2 s . c o m
 * 
 * @param d
 * @param unit
 *            ??
 * @param zone
 *            ?? ???
 * @return
 */
public static boolean isOnTime(Date d, TimeUnit unit, TimeZone zone) {
    BigInteger i = BigInteger.valueOf(d.getTime() + zone.getRawOffset());
    long result = i.mod(BigInteger.valueOf(unit.ms)).longValue();
    return result == 0;
}

From source file:org.owasp.jbrofuzz.core.FuzzerBigInteger.java

/**
 * <p>Return the next element of the fuzzer during iteration.</p>
 * // w w w . j a  va2  s  . c o m
 * <p>This method should be used to access fuzzing payloads, after
 * construction of the fuzzer object.</p>
 * 
 * @return String   The next fuzzer payload, during the iteration 
 *                process
 * 
 * @author subere@uncon.org
 * @version 2.4
 * @since 1.2
 */
public String next() {

    final StringBuffer output = new StringBuffer("");

    // Replacive Prototype
    if (maxValue.compareTo(BigInteger.valueOf(payloads.size())) == 0) {

        output.append(payloads.get(cValue.intValue()));
        cValue = cValue.add(BigInteger.ONE);

    }
    // Recursive Prototype
    else {

        BigInteger val = cValue;
        // Perform division on a stack
        final Stack<BigInteger> stack = new Stack<BigInteger>();
        while (val.compareTo(BigInteger.valueOf(payloads.size())) >= 0) {

            stack.push(val.mod(BigInteger.valueOf(payloads.size())));
            val = val.divide(BigInteger.valueOf(payloads.size()));

        }
        // Append the relevant empty positions with the first element
        // identified
        output.append(StringUtils.leftPad(payloads.get(val.intValue()), len - stack.size(), payloads.get(0)));
        while (!stack.isEmpty()) {
            output.append(payloads.get(stack.pop().intValue()));
        }

        cValue = cValue.add(BigInteger.ONE);

    }

    return output.toString();

}

From source file:de.jfachwert.math.Bruch.java

/**
 * Liefert einen gekuerzten Bruch zurueck. So wird z.B. der Bruch "2/4" als
 * "1/2" zurueckgegeben./*from   w w  w  .ja v a2  s.c o  m*/
 *
 * @return gekuerzter Bruch
 */
public Bruch kuerzen() {
    BigInteger z = getZaehler();
    BigInteger n = getNenner();
    for (Primzahl p = Primzahl.first(); p.toBigInteger().compareTo(n) < 0; p = p.next()) {
        BigInteger teiler = p.toBigInteger();
        while (z.mod(teiler).equals(BigInteger.ZERO) && (n.mod(teiler).equals(BigInteger.ZERO))) {
            z = z.divide(teiler);
            n = n.divide(teiler);
        }
    }
    return Bruch.of(z, n);
}

From source file:burstcoin.observer.service.AssetService.java

private String convertPrice(String priceString, int decimals) {
    BigInteger price = new BigInteger(priceString);
    BigInteger amount = price.multiply(new BigInteger("" + (long) Math.pow(10, decimals)));
    String negative = "";
    String afterComma = "";
    String fractionalPart = amount.mod(new BigInteger("100000000")).toString();
    amount = amount.divide(new BigInteger("100000000"));
    if (amount.compareTo(BigInteger.ZERO) < 0) {
        amount = amount.abs();//w  ww  .  ja v  a 2 s  .c o  m
        negative = "-";
    }
    if (!fractionalPart.equals("0")) {
        afterComma = ".";
        for (int i = fractionalPart.length(); i < 8; i++) {
            afterComma += "0";
        }
        afterComma += fractionalPart.replace("0+$", "");
    }
    String result = negative + amount + afterComma;
    while (result.lastIndexOf("0") == result.length() - 1 && result.contains(".")) {
        result = result.substring(0, result.length() - 1);
    }
    if (result.lastIndexOf(".") == result.length() - 1) {
        result = result.substring(0, result.length() - 1);
    }
    return result;
}

From source file:org.hyperledger.fabric.sdk.MemberServicesImpl.java

/**
 * Process a batch of tcerts after having retrieved them from the TCA.
 *///from  w ww.ja  v  a2  s  .  c  o m
private List<TCert> processTCertBatch(GetTCertBatchRequest req, TCertCreateSetResp resp)
        throws NoSuchPaddingException, InvalidKeyException, NoSuchAlgorithmException, IllegalBlockSizeException,
        BadPaddingException, InvalidAlgorithmParameterException, CryptoException, IOException {
    String enrollKey = req.getEnrollment().getKey();
    byte[] tCertOwnerKDFKey = resp.getCerts().getKey().toByteArray();
    List<Ca.TCert> tCerts = resp.getCerts().getCertsList();

    byte[] byte1 = new byte[] { 1 };
    byte[] byte2 = new byte[] { 2 };

    byte[] tCertOwnerEncryptKey = Arrays.copyOfRange(cryptoPrimitives.calculateMac(tCertOwnerKDFKey, byte1), 0,
            32);
    byte[] expansionKey = cryptoPrimitives.calculateMac(tCertOwnerKDFKey, byte2);

    List<TCert> tCertBatch = new ArrayList<>(tCerts.size());

    // Loop through certs and extract private keys
    for (Ca.TCert tCert : tCerts) {
        X509Certificate x509Certificate;
        try {
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            x509Certificate = (X509Certificate) cf.generateCertificate(tCert.getCert().newInput());
        } catch (Exception ex) {
            logger.debug("Warning: problem parsing certificate bytes; retrying ... ", ex);
            continue;
        }

        // extract the encrypted bytes from extension attribute
        byte[] tCertIndexCT = fromDer(x509Certificate.getExtensionValue(TCERT_ENC_TCERT_INDEX));
        byte[] tCertIndex = cryptoPrimitives.aesCBCPKCS7Decrypt(tCertOwnerEncryptKey, tCertIndexCT);

        byte[] expansionValue = cryptoPrimitives.calculateMac(expansionKey, tCertIndex);

        // compute the private key
        BigInteger k = new BigInteger(1, expansionValue);
        BigInteger n = ((ECPrivateKey) cryptoPrimitives.ecdsaKeyFromPrivate(Hex.decode(enrollKey)))
                .getParameters().getN().subtract(BigInteger.ONE);
        k = k.mod(n).add(BigInteger.ONE);

        BigInteger D = ((ECPrivateKey) cryptoPrimitives.ecdsaKeyFromPrivate(Hex.decode(enrollKey))).getD()
                .add(k);
        D = D.mod(((ECPrivateKey) cryptoPrimitives.ecdsaKeyFromPrivate(Hex.decode(enrollKey))).getParameters()
                .getN());

        // Put private and public key in returned tcert
        TCert tcert = new TCert(tCert.getCert().toByteArray(), cryptoPrimitives.ecdsaKeyFromBigInt(D));

        tCertBatch.add(tcert);
    }

    if (tCertBatch.size() == 0) {
        throw new RuntimeException("Failed fetching TCertBatch. No valid TCert received.");
    }

    return tCertBatch;
}

From source file:eu.dety.burp.joseph.attacks.bleichenbacher_pkcs1.BleichenbacherPkcs1DecryptionAttackExecutor.java

/**
 * @param originalMessage//from www . j a  va2s  .c om
 *            original message to be changed
 * @param si
 *            factor
 * @return Prepared message as byte array
 */
private byte[] prepareMsg(final BigInteger originalMessage, final BigInteger si) {
    byte[] msg;
    BigInteger tmp;

    // encrypt: si^e mod n
    tmp = si.modPow(this.pubKey.getPublicExponent(), this.pubKey.getModulus());

    // blind: c0*(si^e) mod n
    // or: m*si mod n (in case of plaintext m_Oracle)
    tmp = originalMessage.multiply(tmp);
    tmp = tmp.mod(this.pubKey.getModulus());
    // get bytes
    msg = correctSize(tmp.toByteArray(), this.blockSize, true);

    return msg;
}