Example usage for java.math BigInteger toString

List of usage examples for java.math BigInteger toString

Introduction

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

Prototype

public String toString(int radix) 

Source Link

Document

Returns the String representation of this BigInteger in the given radix.

Usage

From source file:io.pyd.synchro.SyncJob.java

public static String computeMD5(File f) {
    MessageDigest digest;//from   w w  w  .  ja va  2  s  .c o  m
    try {
        digest = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e1) {
        e1.printStackTrace();
        return "";
    }
    InputStream is;
    try {
        is = new FileInputStream(f);
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
        return "";
    }
    byte[] buffer = new byte[8192];
    int read = 0;
    try {
        while ((read = is.read(buffer)) > 0) {
            digest.update(buffer, 0, read);
        }
        byte[] md5sum = digest.digest();
        BigInteger bigInt = new BigInteger(1, md5sum);
        String output = bigInt.toString(16);
        if (output.length() < 32) {
            // PAD WITH 0
            while (output.length() < 32)
                output = "0" + output;
        }
        return output;
    } catch (IOException e) {
        // throw new RuntimeException("Unable to process file for MD5", e);
        return "";
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            // throw new
            // RuntimeException("Unable to close input stream for MD5 calculation",
            // e);
            return "";
        }
    }
}

From source file:MegaHandler.java

private int login_process(JSONObject json, long[] password_aes) throws IOException {

    String master_key_b64 = null;
    try {/*  www .j a v a 2s  .co m*/
        master_key_b64 = json.getString("k");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    if (master_key_b64 == null || master_key_b64.isEmpty())
        return -1;

    long[] encrypted_master_key = MegaCrypt.base64_to_a32(master_key_b64);
    master_key = MegaCrypt.decrypt_key(encrypted_master_key, password_aes);

    if (json.has("csid")) {
        String encrypted_rsa_private_key_b64 = null;
        try {
            encrypted_rsa_private_key_b64 = json.getString("privk");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        long[] encrypted_rsa_private_key = MegaCrypt.base64_to_a32(encrypted_rsa_private_key_b64);
        long[] rsa_private_key = MegaCrypt.decrypt_key(encrypted_rsa_private_key, master_key);
        String private_key = MegaCrypt.a32_to_str(rsa_private_key);

        this.rsa_private_key = new BigInteger[4];
        for (int i = 0; i < 4; i++) {
            int l = ((((int) private_key.charAt(0)) * 256 + ((int) private_key.charAt(1)) + 7) / 8) + 2;
            this.rsa_private_key[i] = MegaCrypt.mpi_to_int(private_key.substring(0, l));
            private_key = private_key.substring(l);
        }

        BigInteger encrypted_sid = null;
        try {
            encrypted_sid = MegaCrypt.mpi_to_int(MegaCrypt.base64_url_decode(json.getString("csid")));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        BigInteger modulus = this.rsa_private_key[0].multiply(this.rsa_private_key[1]);
        BigInteger privateExponent = this.rsa_private_key[2];

        BigInteger sid = null;
        try {
            PrivateKey privateKey = KeyFactory.getInstance("RSA")
                    .generatePrivate(new RSAPrivateKeySpec(modulus, privateExponent));
            Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            // PyCrypt can handle >256 bit length... what the fuck... sometimes i get 257
            if (encrypted_sid.toByteArray().length > 256) {
                Random rg = new Random();
                sequence_number = rg.nextInt(Integer.MAX_VALUE);
                return -2; // lets get a new seession
            }
            sid = new BigInteger(cipher.doFinal(encrypted_sid.toByteArray()));
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }

        String sidS = sid.toString(16);
        if (sidS.length() % 2 != 0)
            sidS = "0" + sidS;
        try {
            byte[] sidsnohex = MegaCrypt.decodeHexString(sidS);
            this.sid = MegaCrypt.base64_url_encode(new String(sidsnohex, "ISO-8859-1").substring(0, 43));
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }
    return 0;
}

From source file:com.udojava.evalex.Expression.java

/**
 * Implementation of the <i>Shunting Yard</i> algorithm to transform an
 * infix expression to a RPN expression.
 *
 * @param expression The input expression in infx.
 * @return A RPN representation of the expression, with each token as a list
 * member./*  w ww  . j  a va  2 s .  c  om*/
 */
private List<String> shuntingYard(String expression) {
    List<String> outputQueue = new ArrayList<>();
    Stack<String> stack = new Stack<>();

    Tokenizer tokenizer = new Tokenizer(expression);

    String lastFunction = null;
    String previousToken = null;
    while (tokenizer.hasNext()) {
        String token = tokenizer.next();
        if (isNumber(token)) {
            if (token.startsWith("x")) {

                BigInteger bd = new BigInteger(token.substring(1), 16);
                outputQueue.add(bd.toString(10));
            } else if (token.startsWith("b")) {
                BigInteger bd = new BigInteger(token.substring(1), 2);
                outputQueue.add(bd.toString(10));
            } else if (token.startsWith("o")) {
                BigInteger bd = new BigInteger(token.substring(1), 8);
                outputQueue.add(bd.toString(10));
            } else {
                outputQueue.add(token);
            }
        } else if (mainVars.containsKey(token)) {
            outputQueue.add(token);
        } else if (functions.containsKey(token.toUpperCase(Locale.ROOT))) {
            stack.push(token);
            lastFunction = token;
        } else if ((Character.isLetter(token.charAt(0)) || token.charAt(0) == '_')
                && !operators.containsKey(token)) {
            mainVars.put(token, new MyComplex(0, 0)); // create variable
            outputQueue.add(token);
            //stack.push(token);
        } else if (",".equals(token)) {
            if (operators.containsKey(previousToken)) {
                throw new ExpressionException("Missing parameter(s) for operator " + previousToken
                        + " at character position " + (tokenizer.getPos() - 1 - previousToken.length()));
            }
            while (!stack.isEmpty() && !"(".equals(stack.peek())) {
                outputQueue.add(stack.pop());
            }
            if (stack.isEmpty()) {
                throw new ExpressionException("Parse error for function '" + lastFunction + "'");
            }
        } else if (operators.containsKey(token)) {
            if (",".equals(previousToken) || "(".equals(previousToken)) {
                throw new ExpressionException("Missing parameter(s) for operator " + token
                        + " at character position " + (tokenizer.getPos() - token.length()));
            }
            Operator o1 = operators.get(token);
            String token2 = stack.isEmpty() ? null : stack.peek();
            while (token2 != null && operators.containsKey(token2)
                    && ((o1.isLeftAssoc() && o1.getPrecedence() <= operators.get(token2).getPrecedence())
                            || (o1.getPrecedence() < operators.get(token2).getPrecedence()))) {
                outputQueue.add(stack.pop());
                token2 = stack.isEmpty() ? null : stack.peek();
            }
            stack.push(token);
        } else if ("(".equals(token)) {
            if (previousToken != null) {
                if (isNumber(previousToken)) {
                    throw new ExpressionException(
                            "Missing operator at character position " + tokenizer.getPos());
                }
                // if the ( is preceded by a valid function, then it
                // denotes the start of a parameter list
                if (functions.containsKey(previousToken.toUpperCase(Locale.ROOT))) {
                    outputQueue.add(token);
                }
            }
            stack.push(token);
        } else if (")".equals(token)) {
            if (operators.containsKey(previousToken)) {
                throw new ExpressionException("Missing parameter(s) for operator " + previousToken
                        + " at character position " + (tokenizer.getPos() - 1 - previousToken.length()));
            }
            while (!stack.isEmpty() && !"(".equals(stack.peek())) {
                outputQueue.add(stack.pop());
            }
            if (stack.isEmpty()) {
                throw new ExpressionException("Mismatched parentheses");
            }
            stack.pop();
            if (!stack.isEmpty() && functions.containsKey(stack.peek().toUpperCase(Locale.ROOT))) {
                outputQueue.add(stack.pop());
            }
        }
        previousToken = token;
    }
    while (!stack.isEmpty()) {
        String element = stack.pop();
        if ("(".equals(element) || ")".equals(element)) {
            throw new ExpressionException("Mismatched parentheses");
        }

        if (!operators.containsKey(element)) {
            throw new ExpressionException("Unknown operator or function: " + element);
        }
        outputQueue.add(element);
    }
    return outputQueue;
}

From source file:compiler.downloader.MegaHandler.java

private int login_process(JSONObject json, long[] password_aes) throws IOException {

    String master_key_b64 = null;
    try {/*ww  w .  ja  va2s  .c  om*/
        master_key_b64 = json.getString("k");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    if (master_key_b64 == null || master_key_b64.isEmpty()) {
        return -1;
    }

    long[] encrypted_master_key = MegaCrypt.base64_to_a32(master_key_b64);
    master_key = MegaCrypt.decrypt_key(encrypted_master_key, password_aes);

    if (json.has("csid")) {
        String encrypted_rsa_private_key_b64 = null;
        try {
            encrypted_rsa_private_key_b64 = json.getString("privk");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        long[] encrypted_rsa_private_key = MegaCrypt.base64_to_a32(encrypted_rsa_private_key_b64);
        long[] rsa_private_key = MegaCrypt.decrypt_key(encrypted_rsa_private_key, master_key);
        String private_key = MegaCrypt.a32_to_str(rsa_private_key);

        BigInteger[] rsa_private_key1 = new BigInteger[4];
        for (int i = 0; i < 4; i++) {
            int l = ((((int) private_key.charAt(0)) * 256 + ((int) private_key.charAt(1)) + 7) / 8) + 2;
            rsa_private_key1[i] = MegaCrypt.mpi_to_int(private_key.substring(0, l));
            private_key = private_key.substring(l);
        }

        BigInteger encrypted_sid = null;
        try {
            encrypted_sid = MegaCrypt.mpi_to_int(MegaCrypt.base64_url_decode(json.getString("csid")));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        BigInteger modulus = rsa_private_key1[0].multiply(rsa_private_key1[1]);
        BigInteger privateExponent = rsa_private_key1[2];

        BigInteger sid = null;
        try {
            PrivateKey privateKey = KeyFactory.getInstance("RSA")
                    .generatePrivate(new RSAPrivateKeySpec(modulus, privateExponent));
            Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            // PyCrypt can handle >256 bit length... what the fuck... sometimes i get 257
            if (encrypted_sid.toByteArray().length > 256) {
                Random rg = new Random();
                sequence_number = rg.nextInt(Integer.MAX_VALUE);
                return -2; // lets get a new seession
            }
            sid = new BigInteger(cipher.doFinal(encrypted_sid.toByteArray()));
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }

        String sidS = sid.toString(16);
        if (sidS.length() % 2 != 0) {
            sidS = "0" + sidS;
        }
        try {
            byte[] sidsnohex = MegaCrypt.decodeHexString(sidS);
            this.sid = MegaCrypt.base64_url_encode(new String(sidsnohex, "ISO-8859-1").substring(0, 43));
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }
    return 0;
}

From source file:net.pms.util.Rational.java

/**
 * Used internally to generate a hexadecimal rational string representation
 * from two {@link BigInteger}s.//from   w  w  w .  j  av  a2 s.c o m
 *
 * @param numerator the numerator.
 * @param denominator the denominator.
 * @return The hexadecimal rational string representation.
 */
@Nonnull
protected static String generateRationalHexString(@Nonnull BigInteger numerator,
        @Nonnull BigInteger denominator) {
    if (denominator.signum() == 0) {
        if (numerator.signum() == 0) {
            return "NaN";
        }
        return numerator.signum() > 0 ? "\u221e" : "-\u221e";
    }
    if (BigInteger.ONE.equals(denominator)) {
        return numerator.toString(16);
    }
    return numerator.toString(16) + "/" + denominator.toString(16);
}

From source file:org.cesecore.certificates.certificate.CertificateStoreSessionBean.java

License:asdf

@Override
public CertificateStatus getStatus(String issuerDN, BigInteger serno) {
    if (log.isTraceEnabled()) {
        log.trace(">getStatus(), dn:" + issuerDN + ", serno=" + serno.toString(16));
    }/*from   ww  w  .  j av  a 2  s  . co  m*/
    // First make a DN in our well-known format
    final String dn = CertTools.stringToBCDNString(issuerDN);

    try {
        Collection<CertificateData> coll = CertificateData.findByIssuerDNSerialNumber(entityManager, dn,
                serno.toString());
        if (coll.size() > 1) {
            final String msg = INTRES.getLocalizedMessage("store.errorseveralissuerserno", issuerDN,
                    serno.toString(16));
            log.error(msg);
        }

        for (CertificateData data : coll) {
            final CertificateStatus result = getCertificateStatus(data);
            if (log.isTraceEnabled()) {
                log.trace("<getStatus() returned " + result + " for cert number " + serno.toString(16));
            }
            return result;
        }
        if (log.isTraceEnabled()) {
            log.trace(
                    "<getStatus() did not find certificate with dn " + dn + " and serno " + serno.toString(16));
        }
    } catch (Exception e) {
        throw new EJBException(e);
    }
    return CertificateStatus.NOT_AVAILABLE;
}

From source file:com.servoy.j2db.util.Utils.java

public static String calculateMD5HashBase16(String input) {
    String result = null;//from   ww w .  j  a v a  2s . co  m
    try {
        MessageDigest md = MessageDigest.getInstance("MD5"); //$NON-NLS-1$
        byte[] messageDigest = md.digest(input.getBytes("UTF-8")); //$NON-NLS-1$
        BigInteger number = new BigInteger(1, messageDigest);
        result = number.toString(16);
        if (result.length() < 32) {
            for (int i = 1; i <= 32 - result.length(); i++)
                result = '0' + result;
        }
    } catch (Exception e) {
        Debug.error(e);
    }
    return result;
}

From source file:org.cesecore.certificates.certificate.CertificateStoreSessionBean.java

License:asdf

@Override
public String findUsernameByCertSerno(final BigInteger serno, final String issuerdn) {
    if (log.isTraceEnabled()) {
        log.trace(">findUsernameByCertSerno(), serno: " + serno.toString(16) + ", issuerdn: " + issuerdn);
    }// w w w  .j  a  va2s  . co  m
    final String ret = CertificateData.findLastUsernameByIssuerDNSerialNumber(entityManager,
            CertTools.stringToBCDNString(issuerdn), serno.toString());
    if (log.isTraceEnabled()) {
        log.trace("<findUsernameByCertSerno(), ret=" + ret);
    }
    return ret;
}

From source file:org.cesecore.certificates.certificate.CertificateStoreSessionBean.java

License:asdf

@Override
public CertificateStatusHolder getCertificateAndStatus(String issuerDN, BigInteger serno) {
    if (log.isTraceEnabled()) {
        log.trace(">getCertificateAndStatus(), dn:" + issuerDN + ", serno=" + serno.toString(16));
    }/*from   w ww . ja  va 2 s .com*/
    // First make a DN in our well-known format
    final String dn = CertTools.stringToBCDNString(issuerDN);
    Collection<CertificateData> collection = CertificateData.findByIssuerDNSerialNumber(entityManager, dn,
            serno.toString());
    if (collection.size() > 1) {
        final String msg = INTRES.getLocalizedMessage("store.errorseveralissuerserno", issuerDN,
                serno.toString(16));
        log.error(msg);
    }
    for (CertificateData data : collection) {
        final CertificateStatus result = getCertificateStatus(data);
        if (log.isTraceEnabled()) {
            log.trace("<getStatus() returned " + result + " for cert number " + serno.toString(16));
        }
        return new CertificateStatusHolder(data.getCertificate(entityManager), result);
    }
    if (log.isTraceEnabled()) {
        log.trace("<getCertificateAndStatus() did not find certificate with dn " + dn + " and serno "
                + serno.toString(16));
    }
    return new CertificateStatusHolder(null, CertificateStatus.NOT_AVAILABLE);
}

From source file:org.cesecore.certificates.certificate.CertificateStoreSessionBean.java

License:asdf

@Override
public boolean isRevoked(String issuerDN, BigInteger serno) {
    if (log.isTraceEnabled()) {
        log.trace(">isRevoked(), dn:" + issuerDN + ", serno=" + serno.toString(16));
    }/*from w  w w.  j a v  a2s . c o m*/
    // First make a DN in our well-known format
    String dn = CertTools.stringToBCDNString(issuerDN);
    boolean ret = false;
    try {
        Collection<CertificateData> coll = CertificateData.findByIssuerDNSerialNumber(entityManager, dn,
                serno.toString());
        if (coll.size() > 0) {
            if (coll.size() > 1) {
                final String msg = INTRES.getLocalizedMessage("store.errorseveralissuerserno", issuerDN,
                        serno.toString(16));
                log.error(msg);
            }
            Iterator<CertificateData> iter = coll.iterator();
            while (iter.hasNext()) {
                CertificateData data = iter.next();
                // if any of the certificates with this serno is revoked, return true
                if (data.getStatus() == CertificateConstants.CERT_REVOKED) {
                    ret = true;
                    break;
                }
            }
        } else {
            // If there are no certificates with this serial number, return true (=revoked). Better safe than sorry!
            ret = true;
            if (log.isTraceEnabled()) {
                log.trace("isRevoked() did not find certificate with dn " + dn + " and serno "
                        + serno.toString(16));
            }
        }
    } catch (Exception e) {
        throw new EJBException(e);
    }
    if (log.isTraceEnabled()) {
        log.trace("<isRevoked() returned " + ret);
    }
    return ret;
}