List of usage examples for java.math BigInteger toString
public String toString(int radix)
From source file:com.dgwave.osrs.OsrsClient.java
private String bytesToHex(byte[] bytes) { String s = new String(); BigInteger bi = new BigInteger(1, bytes); // Format to hexadecimal s = bi.toString(16); // 120ff0 if (s.length() % 2 != 0) { // Pad with 0 s = "0" + s; }//from ww w . java 2 s .com return s; }
From source file:piramide.multimodal.applicationserver.rest.DirectoriesManager.java
private String encode(String arg) { try {/* ww w. j av a 2 s . c o m*/ final MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(arg.getBytes()); byte[] md5sum = digest.digest(); final BigInteger bigInt = new BigInteger(1, md5sum); final String output = bigInt.toString(16); return output; } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("MD5 required: " + e.getMessage(), e); } }
From source file:de.mpg.escidoc.pubman.sword.PubManDepositServlet.java
public boolean checkChecksum(InputStream fis, String md5) throws NoSuchAlgorithmException, IOException { boolean check = false; byte[] buffer = new byte[1024]; String checkCalc = ""; MessageDigest md = MessageDigest.getInstance("MD5"); int numRead;//from w w w. j a v a 2 s . com do { numRead = fis.read(buffer); if (numRead > 0) { md.update(buffer, 0, numRead); } } while (numRead != -1); fis.close(); byte[] digest = md.digest(); BigInteger bigInt = new BigInteger(1, digest); checkCalc = bigInt.toString(16); while (checkCalc.length() < 32) { checkCalc = "0" + checkCalc; } if (md5.equals(checkCalc)) { check = true; } return check; }
From source file:org.ethereum.validator.ProofOfWorkRule.java
@Override public boolean isValid(Block block) { BlockHeader header = block.getHeader(); co.rsk.bitcoinj.core.NetworkParameters bitcoinNetworkParameters = SystemProperties.CONFIG .getBlockchainConfig().getCommonConstants().getBridgeConstants().getBtcParams(); byte[] bitcoinMergedMiningCoinbaseTransactionCompressed = header .getBitcoinMergedMiningCoinbaseTransaction(); co.rsk.bitcoinj.core.BtcBlock bitcoinMergedMiningBlock = bitcoinNetworkParameters.getDefaultSerializer() .makeBlock(header.getBitcoinMergedMiningHeader()); co.rsk.bitcoinj.core.PartialMerkleTree bitcoinMergedMiningMerkleBranch = new co.rsk.bitcoinj.core.PartialMerkleTree( bitcoinNetworkParameters, header.getBitcoinMergedMiningMerkleProof(), 0); BigInteger target = DifficultyUtils.difficultyToTarget(header.getDifficultyBI()); BigInteger bitcoinMergedMiningBlockHashBI = bitcoinMergedMiningBlock.getHash().toBigInteger(); if (bitcoinMergedMiningBlockHashBI.compareTo(target) > 0) { logger.error("Hash {} is higher than target {}", bitcoinMergedMiningBlockHashBI.toString(16), target.toString(16));//w w w.ja v a2s. c o m 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.spongycastle.util.Arrays.concatenate(RskMiningConstants.RSK_TAG, header.getHashForMergedMining()); List<Byte> bitcoinMergedMiningCoinbaseTransactionTailAsList = java.util.Arrays .asList(ArrayUtils.toObject(bitcoinMergedMiningCoinbaseTransactionTail)); List<Byte> expectedCoinbaseMessageBytesAsList = java.util.Arrays .asList(ArrayUtils.toObject(expectedCoinbaseMessageBytes)); int rskTagPosition = Collections.lastIndexOfSubList(bitcoinMergedMiningCoinbaseTransactionTailAsList, expectedCoinbaseMessageBytesAsList); if (rskTagPosition == -1) { logger.error( "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.error("bitcoin coinbase transaction tag position is bigger than expected 64. Actual: {}.", Integer.toString(rskTagPosition)); return false; } List<Byte> rskTagAsList = java.util.Arrays.asList(ArrayUtils.toObject(RskMiningConstants.RSK_TAG)); if (rskTagPosition != Collections.lastIndexOfSubList(bitcoinMergedMiningCoinbaseTransactionTailAsList, rskTagAsList)) { logger.error("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.error("More than 128 bytes after ROOOTSTOCK tag"); return false; } SHA256Digest digest = new SHA256Digest(bitcoinMergedMiningCoinbaseTransactionMidstate); digest.update(bitcoinMergedMiningCoinbaseTransactionTail, 0, bitcoinMergedMiningCoinbaseTransactionTail.length); byte[] bitcoinMergedMiningCoinbaseTransactionOneRoundOfHash = new byte[32]; digest.doFinal(bitcoinMergedMiningCoinbaseTransactionOneRoundOfHash, 0); co.rsk.bitcoinj.core.Sha256Hash bitcoinMergedMiningCoinbaseTransactionHash = co.rsk.bitcoinj.core.Sha256Hash .wrapReversed( co.rsk.bitcoinj.core.Sha256Hash.hash(bitcoinMergedMiningCoinbaseTransactionOneRoundOfHash)); List<co.rsk.bitcoinj.core.Sha256Hash> txHashesInTheMerkleBranch = new ArrayList<>(); co.rsk.bitcoinj.core.Sha256Hash merkleRoot = bitcoinMergedMiningMerkleBranch .getTxnHashAndMerkleRoot(txHashesInTheMerkleBranch); if (!merkleRoot.equals(bitcoinMergedMiningBlock.getMerkleRoot())) { logger.error("bitcoin merkle root of bitcoin block does not match the merkle root of merkle branch"); return false; } if (!txHashesInTheMerkleBranch.contains(bitcoinMergedMiningCoinbaseTransactionHash)) { logger.error("bitcoin coinbase transaction {} not included in merkle branch", bitcoinMergedMiningCoinbaseTransactionHash); return false; } return true; }
From source file:edu.mayo.qdm.webapp.rest.store.Md5HashFileSystemResolver.java
/** * Gets the md5 hash./*from w w w .j a v a 2 s . c o m*/ * * @param token the token * @return the md5 hash */ protected String getMd5Hash(String token) { MessageDigest m; try { m = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); } m.update(token.getBytes()); byte[] digest = m.digest(); BigInteger bigInt = new BigInteger(1, digest); String hashtext = bigInt.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; }
From source file:cross.datastructures.pipeline.ResultAwareCommandPipeline.java
/** * Calculates a byte-level digest of the given files. * * @param files the files to calculate the digest for. * @return the hexadecimal, zero-padded digest, or null if any exceptions * occurred/*from w w w . ja v a 2 s. c om*/ */ public String digest(Collection<File> files) { try { MessageDigest digest = MessageDigest.getInstance("SHA-1"); for (File file : files) { try (InputStream is = Files.newInputStream(file.toPath(), StandardOpenOption.READ)) { byte[] buffer = new byte[8192]; int read = 0; while ((read = is.read(buffer)) > 0) { digest.update(buffer, 0, read); } } catch (IOException ioex) { Logger.getLogger(ResultAwareCommandPipeline.class.getName()).log(Level.SEVERE, null, ioex); return null; } } byte[] sha1 = digest.digest(); BigInteger bigInt = new BigInteger(1, sha1); return StringUtils.leftPad(bigInt.toString(16), 40, "0"); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(ResultAwareCommandPipeline.class.getName()).log(Level.SEVERE, null, ex); } return null; }
From source file:com.artivisi.iso8583.Message.java
public void calculateBitmap() { LOGGER.debug("Number of active Data Element [{}]", dataElementContent.size()); BigInteger bitmap = BigInteger.ZERO.setBit(128); for (Integer de : dataElementContent.keySet()) { LOGGER.debug("Set active flag for Data Element [{}]", de); if (de > 64) { bitmap = bitmap.setBit(128 - 1); }/* w w w .j a va2 s . c o m*/ bitmap = bitmap.setBit(128 - de); } LOGGER.debug("Final bitmap bin : [{}]", bitmap.toString(2).substring(1)); LOGGER.debug("Final bitmap hex : [{}]", bitmap.toString(16).substring(1)); setPrimaryBitmapStream(StringUtils.rightPad(bitmap.toString(16).substring(1, 16), 16, "0")); if (bitmap.testBit(128 - 1)) { setSecondaryBitmapStream(StringUtils.rightPad(bitmap.toString(16).substring(17), 16, "0")); } }
From source file:org.openhab.voice.googletts.internal.GoogleCloudAPI.java
/** * Gets a unique filename for a give text, by creating a MD5 hash of it. It * will be preceded by the locale./*from w ww . j a va 2 s.c o m*/ * <p> * Sample: "en-US_00a2653ac5f77063bc4ea2fee87318d3" */ private String getUniqueFilenameForText(String text, String voiceName) { try { byte[] bytesOfMessage = (config.toConfigString() + text).getBytes(UTF_8); MessageDigest md = MessageDigest.getInstance("MD5"); byte[] md5Hash = md.digest(bytesOfMessage); BigInteger bigInt = new BigInteger(1, md5Hash); StringBuilder hashText = new StringBuilder(bigInt.toString(16)); // Now we need to zero pad it if you actually want the full 32 chars. while (hashText.length() < 32) { hashText.insert(0, "0"); } return voiceName + "_" + hashText; } catch (UnsupportedEncodingException | NoSuchAlgorithmException ex) { // should not happen logger.error("Could not create MD5 hash for '{}'", text, ex); return null; } }
From source file:org.ejbca.core.protocol.ws.client.EditUserCommand.java
/** * Runs the command/*from ww w . j a va 2 s . c o m*/ * * @throws IllegalAdminCommandException Error in command args * @throws ErrorAdminCommandException Error running command */ public void execute() throws IllegalAdminCommandException, ErrorAdminCommandException { final UserDataVOWS userdata = new UserDataVOWS(); final String[] myArgs = ParseUserData.getDataFromArgs(this.args, userdata, getPrintStream()); if (myArgs.length < NR_OF_MANDATORY_ARGS || myArgs.length > MAX_NR_OF_ARGS) { usage(); System.exit(-1); // NOPMD, this is not a JEE app } try { userdata.setUsername(myArgs[ARG_USERNAME]); String pwd = myArgs[ARG_PASSWORD]; if (StringUtils.equalsIgnoreCase("null", pwd)) { pwd = null; } userdata.setPassword(pwd); userdata.setClearPwd(myArgs[ARG_CLEARPWD].equalsIgnoreCase("true")); userdata.setSubjectDN(myArgs[ARG_SUBJECTDN]); if (!myArgs[ARG_SUBJECTALTNAME].equalsIgnoreCase("NULL")) { userdata.setSubjectAltName(myArgs[ARG_SUBJECTALTNAME]); } if (!myArgs[ARG_EMAIL].equalsIgnoreCase("NULL")) { userdata.setEmail(myArgs[ARG_EMAIL]); } userdata.setCaName(myArgs[ARG_CA]); userdata.setTokenType(myArgs[ARG_TOKEN]); userdata.setStatus(getStatus(myArgs[ARG_STATUS])); userdata.setEndEntityProfileName(myArgs[ARG_ENDENTITYPROFILE]); userdata.setCertificateProfileName(myArgs[ARG_CERTIFICATEPROFILE]); EndEntityType type = new EndEntityType( EndEntityTypes.getTypesFromHexCode(Integer.parseInt(myArgs[ARG_TYPE]))); if (type.contains(EndEntityTypes.SENDNOTIFICATION)) { userdata.setSendNotification(true); } if (type.contains(EndEntityTypes.KEYRECOVERABLE)) { userdata.setKeyRecoverable(true); } if (myArgs.length > ARG_ISSUERALIAS) { if (!myArgs[ARG_ISSUERALIAS].equalsIgnoreCase("NULL")) { userdata.setHardTokenIssuerName(myArgs[ARG_ISSUERALIAS]); } } if (myArgs.length > ARG_STARTTIME) { if (!myArgs[ARG_STARTTIME].equalsIgnoreCase("NULL")) { userdata.setStartTime(myArgs[ARG_STARTTIME]); } } if (myArgs.length > ARG_ENDTIME) { if (!myArgs[ARG_ENDTIME].equalsIgnoreCase("NULL")) { userdata.setEndTime(myArgs[ARG_ENDTIME]); } } getPrintStream().println("Trying to add user:"); getPrintStream().println("Username: " + userdata.getUsername()); getPrintStream().println("Subject DN: " + userdata.getSubjectDN()); getPrintStream().println("Subject Altname: " + userdata.getSubjectAltName()); getPrintStream().println("Email: " + userdata.getEmail()); getPrintStream().println("CA Name: " + userdata.getCaName()); getPrintStream().println("Type: " + type.getHexValue()); getPrintStream().println("Token: " + userdata.getTokenType()); getPrintStream().println("Status: " + userdata.getStatus()); getPrintStream().println("End entity profile: " + userdata.getEndEntityProfileName()); getPrintStream().println("Certificate profile: " + userdata.getCertificateProfileName()); if (userdata.getHardTokenIssuerName() == null) { getPrintStream().println("Hard Token Issuer Alias: NONE"); } else { getPrintStream().println("Hard Token Issuer Alias: " + userdata.getHardTokenIssuerName()); } if (userdata.getStartTime() == null) { getPrintStream().println("Start time: NONE"); } else { getPrintStream().println("Start time: " + userdata.getStartTime()); } if (userdata.getEndTime() == null) { getPrintStream().println("End time: NONE"); } else { getPrintStream().println("End time: " + userdata.getEndTime()); } { final List<ExtendedInformationWS> eil = userdata.getExtendedInformation(); if (eil != null) { getPrintStream().println("Extended information:"); for (ExtendedInformationWS ei : eil) { getPrintStream().println(" '" + ei.getName() + "' = '" + ei.getValue() + "'"); } } } { final BigInteger bi = userdata.getCertificateSerialNumber(); if (bi != null) { getPrintStream().println(ParseUserData.certificateSerialNumber + "=0x" + bi.toString(16)); } } try { getEjbcaRAWS().editUser(userdata); getPrintStream().println("User '" + userdata.getUsername() + "' has been added/edited."); getPrintStream().println(); } catch (AuthorizationDeniedException_Exception e) { getPrintStream().println("Error : " + e.getMessage()); } catch (UserDoesntFullfillEndEntityProfile_Exception e) { getPrintStream() .println("Error : Given userdata doesn't fullfill end entity profile. : " + e.getMessage()); } } catch (Exception e) { throw new ErrorAdminCommandException(e); } }
From source file:org.broadleafcommerce.cms.file.service.StaticAssetStorageServiceImpl.java
/** * Builds a file system path for the passed in static asset and paramaterMap. * /*from w w w . j a v a 2 s.c o m*/ * @param staticAsset * @param parameterMap * @param useSharedFile * @return */ protected String constructCacheFileName(StaticAsset staticAsset, Map<String, String> parameterMap) { String fileName = staticAsset.getFullUrl(); StringBuilder sb = new StringBuilder(200); sb.append(fileName.substring(0, fileName.lastIndexOf('.'))); sb.append("---"); StringBuilder sb2 = new StringBuilder(200); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss"); if (staticAsset.getAuditable() != null) { sb2.append(format.format(staticAsset.getAuditable().getDateUpdated() == null ? staticAsset.getAuditable().getDateCreated() : staticAsset.getAuditable().getDateUpdated())); } if (parameterMap != null) { for (Map.Entry<String, String> entry : parameterMap.entrySet()) { sb2.append('-'); sb2.append(entry.getKey()); sb2.append('-'); sb2.append(entry.getValue()); } } String digest; try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] messageDigest = md.digest(sb2.toString().getBytes()); BigInteger number = new BigInteger(1, messageDigest); digest = number.toString(16); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } sb.append(pad(digest, 32, '0')); sb.append(fileName.substring(fileName.lastIndexOf('.'))); return sb.toString(); }