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:org.opendatakit.utilities.ODKFileUtils.java

/**
 * MD5's a file. Used in ODKDatabaseImplUtils and EncryptionUtils
 *
 * @param appName the app name/*  w  ww .  j av a2  s.  com*/
 * @param file    the file to hash
 * @return the md5sum of that file
 */
@SuppressWarnings("WeakerAccess")
public static String getNakedMd5Hash(String appName, Object file) {
    InputStream is = null;
    try {
        // CTS (6/15/2010) : stream file through digest instead of handing
        // it the byte[]
        MessageDigest md = MessageDigest.getInstance("MD5");
        int chunkSize = 8192;

        byte[] chunk = new byte[chunkSize];

        // Get the size of the file
        long lLength;
        if (file instanceof File) {
            lLength = ((File) file).length();
        } else if (file instanceof String) {
            lLength = ((String) file).length();
        } else {
            throw new IllegalArgumentException("Bad object to md5");
        }

        if (lLength > Integer.MAX_VALUE) {
            if (file instanceof File) {
                WebLogger.getLogger(appName).e(TAG, "File " + ((File) file).getName() + " is too large");
            } else {
                WebLogger.getLogger(appName).e(TAG, "String is too large to md5");
            }
            return null;
        }

        if (lLength > Integer.MAX_VALUE) {
            throw new RuntimeException("Refusing to cast from long to int with loss of precision");
        }
        //noinspection NumericCastThatLosesPrecision
        int length = (int) lLength;

        if (file instanceof File) {
            is = new FileInputStream((File) file);
        } else {
            is = new ByteArrayInputStream(((String) file).getBytes(CharEncoding.UTF_8));
        }

        int l;
        for (l = 0; l + chunkSize < length; l += chunkSize) {
            // TODO double check that this still works after the change
            if (is.read(chunk, 0, chunkSize) == -1)
                break;
            md.update(chunk, 0, chunkSize);
        }

        int remaining = length - l;
        if (remaining > 0) {
            // TODO double check that this still works after the change
            if (is.read(chunk, 0, remaining) != -1) {
                md.update(chunk, 0, remaining);
            }
        }
        byte[] messageDigest = md.digest();

        BigInteger number = new BigInteger(1, messageDigest);
        String md5 = number.toString(16);
        while (md5.length() < 32)
            md5 = "0" + md5;
        is.close();
        return md5;

    } catch (NoSuchAlgorithmException e) {
        WebLogger.getLogger(appName).e("MD5", e.getMessage());
        return null;

    } catch (FileNotFoundException e) {
        WebLogger.getLogger(appName).e("No Cache File", e.getMessage());
        return null;
    } catch (IOException e) {
        WebLogger.getLogger(appName).e("Problem reading from file", e.getMessage());
        return null;
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                WebLogger.getLogger(appName).printStackTrace(e);
            }
        }
    }

}

From source file:com.board.games.handler.xbtit.XbtitPokerLoginServiceImpl.java

private synchronized String getMD5(String input) {
    try {//from w  ww.  j a  va 2 s. com
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] messageDigest = md.digest(input.getBytes("UTF-8"));
        BigInteger number = new BigInteger(1, messageDigest);
        String hashtext = number.toString(16);
        // Now we need to zero pad it if you actually want the full 32
        // chars.
        while (hashtext.length() < 32) {
            hashtext = "0" + hashtext;
        }
        return hashtext;
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (UnsupportedEncodingException ex) {
        ex.printStackTrace();
    }
    return null;
}

From source file:co.rsk.validators.ProofOfWorkRule.java

@Override
public boolean isValid(BlockHeader header) {
    // TODO: refactor this an move it to another class. Change the Global ProofOfWorkRule to AuthenticationRule.
    // TODO: Make ProofOfWorkRule one of the classes that inherits from AuthenticationRule.
    if (isFallbackMiningPossibleAndBlockSigned(header)) {
        boolean isValidFallbackSignature = validFallbackBlockSignature(constants, header,
                header.getBitcoinMergedMiningHeader());
        if (!isValidFallbackSignature) {
            logger.warn("Fallback signature failed. Header {}", header.getShortHash());
        }//from   w  w  w .ja  v  a 2s.  co  m
        return isValidFallbackSignature;
    }

    co.rsk.bitcoinj.core.NetworkParameters bitcoinNetworkParameters = bridgeConstants.getBtcParams();
    MerkleProofValidator mpValidator;
    try {
        if (blockchainConfig.getConfigForBlock(header.getNumber()).isRskip92()) {
            mpValidator = new Rskip92MerkleProofValidator(header.getBitcoinMergedMiningMerkleProof());
        } else {
            mpValidator = new GenesisMerkleProofValidator(bitcoinNetworkParameters,
                    header.getBitcoinMergedMiningMerkleProof());
        }
    } catch (RuntimeException ex) {
        logger.warn("Merkle proof can't be validated. Header {}", header.getShortHash(), ex);
        return false;
    }

    byte[] bitcoinMergedMiningCoinbaseTransactionCompressed = header
            .getBitcoinMergedMiningCoinbaseTransaction();

    if (bitcoinMergedMiningCoinbaseTransactionCompressed == null) {
        logger.warn("Compressed coinbase transaction does not exist. Header {}", header.getShortHash());
        return false;
    }

    if (header.getBitcoinMergedMiningHeader() == null) {
        logger.warn("Bitcoin merged mining header does not exist. Header {}", header.getShortHash());
        return false;
    }

    BtcBlock bitcoinMergedMiningBlock = bitcoinNetworkParameters.getDefaultSerializer()
            .makeBlock(header.getBitcoinMergedMiningHeader());

    BigInteger target = DifficultyUtils.difficultyToTarget(header.getDifficulty());

    BigInteger bitcoinMergedMiningBlockHashBI = bitcoinMergedMiningBlock.getHash().toBigInteger();

    if (bitcoinMergedMiningBlockHashBI.compareTo(target) > 0) {
        logger.warn("Hash {} is higher than target {}", bitcoinMergedMiningBlockHashBI.toString(16),
                target.toString(16));
        return false;
    }

    byte[] bitcoinMergedMiningCoinbaseTransactionMidstate = new byte[RskMiningConstants.MIDSTATE_SIZE];
    System.arraycopy(bitcoinMergedMiningCoinbaseTransactionCompressed, 0,
            bitcoinMergedMiningCoinbaseTransactionMidstate, 8, RskMiningConstants.MIDSTATE_SIZE_TRIMMED);

    byte[] bitcoinMergedMiningCoinbaseTransactionTail = new byte[bitcoinMergedMiningCoinbaseTransactionCompressed.length
            - RskMiningConstants.MIDSTATE_SIZE_TRIMMED];
    System.arraycopy(bitcoinMergedMiningCoinbaseTransactionCompressed, RskMiningConstants.MIDSTATE_SIZE_TRIMMED,
            bitcoinMergedMiningCoinbaseTransactionTail, 0, bitcoinMergedMiningCoinbaseTransactionTail.length);

    byte[] expectedCoinbaseMessageBytes = org.bouncycastle.util.Arrays.concatenate(RskMiningConstants.RSK_TAG,
            header.getHashForMergedMining());

    List<Byte> bitcoinMergedMiningCoinbaseTransactionTailAsList = Arrays
            .asList(ArrayUtils.toObject(bitcoinMergedMiningCoinbaseTransactionTail));
    List<Byte> expectedCoinbaseMessageBytesAsList = Arrays
            .asList(ArrayUtils.toObject(expectedCoinbaseMessageBytes));

    int rskTagPosition = Collections.lastIndexOfSubList(bitcoinMergedMiningCoinbaseTransactionTailAsList,
            expectedCoinbaseMessageBytesAsList);
    if (rskTagPosition == -1) {
        logger.warn(
                "bitcoin coinbase transaction tail message does not contain expected RSKBLOCK:RskBlockHeaderHash. Expected: {} . Actual: {} .",
                Arrays.toString(expectedCoinbaseMessageBytes),
                Arrays.toString(bitcoinMergedMiningCoinbaseTransactionTail));
        return false;
    }

    /*
    * We check that the there is no other block before the rsk tag, to avoid a possible malleability attack:
    * If we have a mid state with 10 blocks, and the rsk tag, we can also have
    * another mid state with 9 blocks, 64bytes + the rsk tag, giving us two blocks with different hashes but the same spv proof.
    * */
    if (rskTagPosition >= 64) {
        logger.warn("bitcoin coinbase transaction tag position is bigger than expected 64. Actual: {}.",
                Integer.toString(rskTagPosition));
        return false;
    }

    List<Byte> rskTagAsList = Arrays.asList(ArrayUtils.toObject(RskMiningConstants.RSK_TAG));
    int lastTag = Collections.lastIndexOfSubList(bitcoinMergedMiningCoinbaseTransactionTailAsList,
            rskTagAsList);
    if (rskTagPosition != lastTag) {
        logger.warn("The valid RSK tag is not the last RSK tag. Tail: {}.",
                Arrays.toString(bitcoinMergedMiningCoinbaseTransactionTail));
        return false;
    }

    int remainingByteCount = bitcoinMergedMiningCoinbaseTransactionTail.length - rskTagPosition
            - RskMiningConstants.RSK_TAG.length - RskMiningConstants.BLOCK_HEADER_HASH_SIZE;

    if (remainingByteCount > RskMiningConstants.MAX_BYTES_AFTER_MERGED_MINING_HASH) {
        logger.warn("More than 128 bytes after RSK tag");
        return false;
    }

    // TODO test
    long byteCount = Pack.bigEndianToLong(bitcoinMergedMiningCoinbaseTransactionMidstate, 8);
    long coinbaseLength = bitcoinMergedMiningCoinbaseTransactionTail.length + byteCount;
    if (coinbaseLength <= 64) {
        logger.warn("Coinbase transaction must always be greater than 64-bytes long. But it was: {}",
                coinbaseLength);
        return false;
    }

    SHA256Digest digest = new SHA256Digest(bitcoinMergedMiningCoinbaseTransactionMidstate);
    digest.update(bitcoinMergedMiningCoinbaseTransactionTail, 0,
            bitcoinMergedMiningCoinbaseTransactionTail.length);
    byte[] bitcoinMergedMiningCoinbaseTransactionOneRoundOfHash = new byte[32];
    digest.doFinal(bitcoinMergedMiningCoinbaseTransactionOneRoundOfHash, 0);
    Sha256Hash bitcoinMergedMiningCoinbaseTransactionHash = Sha256Hash
            .wrapReversed(Sha256Hash.hash(bitcoinMergedMiningCoinbaseTransactionOneRoundOfHash));

    if (!mpValidator.isValid(bitcoinMergedMiningBlock.getMerkleRoot(),
            bitcoinMergedMiningCoinbaseTransactionHash)) {
        logger.warn("bitcoin merkle branch doesn't match coinbase and state root");
        return false;
    }

    return true;
}

From source file:org.alfresco.repo.virtual.ref.NodeRefRadixHasher.java

@Override
public Pair<String, String> hash(NodeRef nodeRef) {
    String uuid = nodeRef.getId();

    if (uuid.length() != 36) {
        throw new RuntimeException("Invalid noderf id length " + uuid);
    }//from  w  w w . j a v a2 s  .  com

    String bigInt16String = uuid.replaceAll("-", "");
    if (bigInt16String.length() != 32) {
        throw new RuntimeException("Invalid noderf id format " + uuid);
    }

    BigInteger bigIntId = new BigInteger(bigInt16String, 16);
    StoreRef storeRef = nodeRef.getStoreRef();
    String storeProtocolHash = storeProtocolStore.hash(storeRef.getProtocol());
    String storeIdHash = storeIdStore.hash(storeRef.getIdentifier());
    if (storeProtocolHash == null || storeIdHash == null) {
        throw new RuntimeException("Missing hash for " + storeRef);
    }
    String storeHash = storeProtocolHash + storeIdHash;
    return new Pair<String, String>(storeHash, bigIntId.toString(radix));

}

From source file:org.apache.solr.handler.AnalysisRequestHandlerBase.java

/**
 * Converts the list of Tokens to a list of NamedLists representing the tokens.
 *
 * @param tokens  Tokens to convert//from  ww w  .ja v a 2 s  .  com
 * @param context The analysis context
 *
 * @return List of NamedLists containing the relevant information taken from the tokens
 */
private List<NamedList> convertTokensToNamedLists(final List<AttributeSource> tokenList,
        AnalysisContext context) {
    final List<NamedList> tokensNamedLists = new ArrayList<NamedList>();
    final FieldType fieldType = context.getFieldType();
    final AttributeSource[] tokens = tokenList.toArray(new AttributeSource[tokenList.size()]);

    // sort the tokens by absoulte position
    ArrayUtil.mergeSort(tokens, new Comparator<AttributeSource>() {
        public int compare(AttributeSource a, AttributeSource b) {
            return arrayCompare(a.getAttribute(TokenTrackingAttribute.class).getPositions(),
                    b.getAttribute(TokenTrackingAttribute.class).getPositions());
        }

        private int arrayCompare(int[] a, int[] b) {
            int p = 0;
            final int stop = Math.min(a.length, b.length);
            while (p < stop) {
                int diff = a[p] - b[p];
                if (diff != 0)
                    return diff;
                p++;
            }
            // One is a prefix of the other, or, they are equal:
            return a.length - b.length;
        }
    });

    for (int i = 0; i < tokens.length; i++) {
        AttributeSource token = tokens[i];
        final NamedList<Object> tokenNamedList = new SimpleOrderedMap<Object>();
        final String rawText = token.addAttribute(CharTermAttribute.class).toString();

        String text = fieldType.indexedToReadable(rawText);
        tokenNamedList.add("text", text);
        if (!text.equals(rawText)) {
            tokenNamedList.add("raw_text", rawText);
        }

        if (context.getTermsToMatch().contains(rawText)) {
            tokenNamedList.add("match", true);
        }

        token.reflectWith(new AttributeReflector() {
            public void reflect(Class<? extends Attribute> attClass, String key, Object value) {
                // leave out position and term
                if (CharTermAttribute.class.isAssignableFrom(attClass))
                    return;
                if (PositionIncrementAttribute.class.isAssignableFrom(attClass))
                    return;

                String k = attClass.getName() + '#' + key;

                // map keys for "standard attributes":
                if (ATTRIBUTE_MAPPING.containsKey(k)) {
                    k = ATTRIBUTE_MAPPING.get(k);
                }

                // TODO: special handling for payloads - move this to ResponseWriter?
                if (value instanceof Payload) {
                    Payload p = (Payload) value;
                    if (null != p) {
                        BigInteger bi = new BigInteger(p.getData());
                        String ret = bi.toString(16);
                        if (ret.length() % 2 != 0) {
                            // Pad with 0
                            ret = "0" + ret;
                        }
                        value = ret;
                    } else {
                        value = null;
                    }
                }

                tokenNamedList.add(k, value);
            }
        });

        tokensNamedLists.add(tokenNamedList);
    }

    return tokensNamedLists;
}

From source file:org.ambientdynamix.contextplugins.withingsdataplugin.WithingsDataPluginRuntime.java

/**
  * this method returns an md5Hash of a String
  * /*from  w  w  w.  j  a v a 2  s.co  m*/
  * This code is based on the code found at http://code.google.com/p/libra-android/
  *
  *@param A String to be hashed
  */
private String md5Hash(String string) throws Exception {
    MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
    digest.update(string.getBytes());
    byte messageDigest[] = digest.digest();

    // Get the Hex String
    BigInteger bigInt = new BigInteger(1, messageDigest);
    return bigInt.toString(16);
}

From source file:org.ejbca.ui.cmpclient.commands.RevocationRequestCommand.java

@Override
public PKIMessage generatePKIMessage(ParameterContainer parameters) throws Exception {
    boolean verbose = parameters.containsKey(VERBOSE_KEY);

    final X500Name userDN = new X500Name("CN=foo");
    final X500Name issuerDN = new X500Name(parameters.get(ISSUERDN_KEY));
    BigInteger serno = new BigInteger(parameters.get(SERNO_KEY), 16);

    if (verbose) {
        log.info("Creating revocation request with: SubjectDN=" + userDN.toString());
        log.info("Creating revocation request with: IssuerDN=" + issuerDN.toString());
        log.info("Creating revocation request with: CertSerno=" + serno.toString(16));
    }//from www .  j  av  a2  s  .  co  m

    byte[] nonce = CmpClientMessageHelper.getInstance().createSenderNonce();
    byte[] transid = CmpClientMessageHelper.getInstance().createSenderNonce();

    CertTemplateBuilder myCertTemplate = new CertTemplateBuilder();
    myCertTemplate.setIssuer(issuerDN);
    myCertTemplate.setSubject(userDN);
    myCertTemplate.setSerialNumber(new ASN1Integer(serno));

    ExtensionsGenerator extgen = new ExtensionsGenerator();
    extgen.addExtension(Extension.reasonCode, false, getCRLReason(parameters.get(REVOCATION_REASON_KEY)));

    Extensions exts = extgen.generate();

    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(myCertTemplate.build());
    v.add(exts);
    ASN1Sequence seq = new DERSequence(v);

    RevDetails myRevDetails = RevDetails.getInstance(seq);

    RevReqContent myRevReqContent = new RevReqContent(myRevDetails);

    PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(userDN), new GeneralName(issuerDN));
    myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date()));
    // senderNonce
    myPKIHeader.setSenderNonce(new DEROctetString(nonce));
    // TransactionId
    myPKIHeader.setTransactionID(new DEROctetString(transid));
    myPKIHeader.setProtectionAlg(null);
    myPKIHeader.setSenderKID(new byte[0]);

    PKIBody myPKIBody = new PKIBody(PKIBody.TYPE_REVOCATION_REQ, myRevReqContent); // revocation request
    PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);
    return myPKIMessage;
}

From source file:Controller.ComunicacaoInternaMB.java

public String gerarMD5(String senha) throws NoSuchAlgorithmException {
    MessageDigest md = MessageDigest.getInstance("MD5");
    BigInteger hash = new BigInteger(1, md.digest(senha.getBytes()));
    String crypto = hash.toString(16);
    if (crypto.length() % 2 != 0) {
        crypto = "0" + crypto;
    }//from ww w.  j a  v  a2  s  . co  m
    return crypto;
}

From source file:com.neusou.bioroid.image.ImageLoader.java

private String computeDigest(String uri) {
    String s = uri;/*from   ww  w .  j  a v  a  2  s.  c o  m*/
    MessageDigest m;
    try {
        m = MessageDigest.getInstance("MD5");
        m.update(s.getBytes(), 0, s.length());
        BigInteger bi = new BigInteger(1, m.digest());
        String bigInt = bi.toString(16);
        return bigInt;
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return null;
}