List of usage examples for com.google.common.hash Hashing sha256
public static HashFunction sha256()
From source file:org.sonatype.nexus.yum.internal.MetadataProcessor.java
/** * Store primary.xml and update content of repomd.xml accordingly. * * @param repository repository containing primary.xml/repomd.xml * @param repoMDDoc parsed repomd.xml//from www. j a v a 2 s . c om * @param primaryPath path of primary.xml * @return true if repomd.xml changed */ private static boolean updatePrimaryInRepoMD(final Repository repository, final Document repoMDDoc, final String primaryPath) throws Exception { XPath xPath = XPathFactory.newInstance().newXPath(); String primaryHref = xPath.compile("/repomd/data[@type='primary']/location/@href").evaluate(repoMDDoc); if (!Objects.equals(primaryPath, primaryHref)) { log.debug("Updating 'primary' data entry in {}:repomd.xml", repository.getId()); Element primaryEl = (Element) xPath.compile("/repomd/data[@type='primary']").evaluate(repoMDDoc, NODE); StorageFileItem primaryItem = (StorageFileItem) repository.retrieveItem(false, new ResourceStoreRequest("/" + primaryPath)); try (InputStream in = primaryItem.getInputStream(); CountingInputStream cis = new CountingInputStream( new GZIPInputStream(new BufferedInputStream(in)))) { HashCode checksum = Hashes.hash(Hashing.sha256(), cis); primaryEl.getElementsByTagName("open-checksum").item(0).setTextContent(checksum.toString()); primaryEl.getElementsByTagName("open-size").item(0).setTextContent(String.valueOf(cis.getCount())); } primaryItem = (StorageFileItem) repository.retrieveItem(false, new ResourceStoreRequest("/" + primaryPath)); try (InputStream in = primaryItem.getInputStream(); CountingInputStream cis = new CountingInputStream(new BufferedInputStream(in))) { HashCode checksum = Hashes.hash(Hashing.sha256(), cis); primaryEl.getElementsByTagName("checksum").item(0).setTextContent(checksum.toString()); primaryEl.getElementsByTagName("size").item(0).setTextContent(String.valueOf(cis.getCount())); } ((Element) primaryEl.getElementsByTagName("location").item(0)).setAttribute("href", primaryPath); return true; } return false; }
From source file:com.facebook.presto.bloomfilter.BloomFilter.java
public Slice serialize() { byte[] bytes = new byte[0]; byte[] bytesPre = new byte[0]; try {/*from w w w . ja v a 2s .c o m*/ ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput output = new ObjectOutputStream(buffer); output.writeObject(instance); bytes = buffer.toByteArray(); ByteArrayOutputStream bufferPre = new ByteArrayOutputStream(); ObjectOutput outputPre = new ObjectOutputStream(bufferPre); outputPre.writeObject(instancePreFilter); bytesPre = bufferPre.toByteArray(); } catch (Exception ix) { log.error(ix); } // Create hash byte[] bfHash = Hashing.sha256().hashBytes(bytes).asBytes(); // Compress byte[] compressed; try { compressed = compress(bytes); } catch (IOException ix) { log.error(ix); compressed = new byte[0]; } int size = compressed.length; // Compress byte[] compressedPre; try { compressedPre = compress(bytesPre); } catch (IOException ix) { log.error(ix); compressedPre = new byte[0]; } int sizePre = compressedPre.length; // To slice DynamicSliceOutput output = new DynamicSliceOutput(size); // Write hash output.writeBytes(bfHash); // 32 bytes // Write the length of the bloom filter output.appendInt(size); // Write the length of the pre bloom filter output.appendInt(sizePre); // Params output.appendInt(expectedInsertions); output.appendDouble(falsePositivePercentage); // Write the bloom filter output.appendBytes(compressed); // Write the bloom filter output.appendBytes(compressedPre); return output.slice(); }
From source file:net.pterodactylus.sone.data.AlbumImpl.java
@Override public String getFingerprint() { Hasher hash = Hashing.sha256().newHasher(); hash.putString("Album("); hash.putString("ID(").putString(id).putString(")"); hash.putString("Title(").putString(title).putString(")"); hash.putString("Description(").putString(description).putString(")"); if (albumImage != null) { hash.putString("AlbumImage(").putString(albumImage).putString(")"); }/*from ww w . ja v a 2 s. co m*/ /* add nested albums. */ hash.putString("Albums("); for (Album album : albums) { hash.putString(album.getFingerprint()); } hash.putString(")"); /* add images. */ hash.putString("Images("); for (Image image : getImages()) { if (image.isInserted()) { hash.putString(image.getFingerprint()); } } hash.putString(")"); hash.putString(")"); return hash.hash().toString(); }
From source file:net.pterodactylus.sone.data.Profile.java
/** * {@inheritDoc}/*from ww w . ja v a 2 s. c o m*/ */ @Override public String getFingerprint() { Hasher hash = Hashing.sha256().newHasher(); hash.putString("Profile("); if (firstName != null) { hash.putString("FirstName(").putString(firstName).putString(")"); } if (middleName != null) { hash.putString("MiddleName(").putString(middleName).putString(")"); } if (lastName != null) { hash.putString("LastName(").putString(lastName).putString(")"); } if (birthDay != null) { hash.putString("BirthDay(").putInt(birthDay).putString(")"); } if (birthMonth != null) { hash.putString("BirthMonth(").putInt(birthMonth).putString(")"); } if (birthYear != null) { hash.putString("BirthYear(").putInt(birthYear).putString(")"); } if (avatar != null) { hash.putString("Avatar(").putString(avatar).putString(")"); } hash.putString("ContactInformation("); for (Field field : fields) { hash.putString(field.getName()).putString("(").putString(field.getValue()).putString(")"); } hash.putString(")"); hash.putString(")"); return hash.hash().toString(); }
From source file:io.dockstore.webservice.resources.TokenResource.java
@GET @Timed/*from w w w. ja v a 2 s.c om*/ @UnitOfWork @Path("/github.com") @ApiOperation(value = "Add a new github.com token, used by quay.io redirect", notes = "This is used as part of the OAuth 2 web flow. " + "Once a user has approved permissions for Collaboratory" + "Their browser will load the redirect URI which should resolve here", response = Token.class) public Token addGithubToken(@QueryParam("code") String code) { String accessToken; String error; int count = MAX_ITERATIONS; while (true) { Optional<String> asString = ResourceUtilities.asString(GIT_URL + "login/oauth/access_token?code=" + code + "&client_id=" + githubClientID + "&client_secret=" + githubClientSecret, null, client); if (asString.isPresent()) { Map<String, String> split = Splitter.on('&').trimResults().withKeyValueSeparator("=") .split(asString.get()); accessToken = split.get("access_token"); error = split.get("error"); } else { throw new CustomWebApplicationException("Could not retrieve github.com token based on code", HttpStatus.SC_BAD_REQUEST); } if (error != null && "bad_verification_code".equals(error)) { LOG.info("ERROR: {}", error); if (--count == 0) { throw new CustomWebApplicationException("Could not retrieve github.com token based on code", HttpStatus.SC_BAD_REQUEST); } else { LOG.info("trying again..."); } } else if (accessToken != null && !accessToken.isEmpty()) { LOG.info("Successfully recieved accessToken: {}", accessToken); break; } else { LOG.info("Retrieving accessToken was unsuccessful"); throw new CustomWebApplicationException("Could not retrieve github.com token based on code", HttpStatus.SC_BAD_REQUEST); } } GitHubClient githubClient = new GitHubClient(); githubClient.setOAuth2Token(accessToken); long userID; String githubLogin; Token dockstoreToken = null; Token githubToken = null; try { UserService uService = new UserService(githubClient); org.eclipse.egit.github.core.User githubUser = uService.getUser(); githubLogin = githubUser.getLogin(); } catch (IOException ex) { throw new CustomWebApplicationException("Token ignored due to IOException", HttpStatus.SC_CONFLICT); } User user = userDAO.findByUsername(githubLogin); if (user == null) { user = new User(); user.setUsername(githubLogin); userID = userDAO.create(user); // CREATE DOCKSTORE TOKEN final Random random = new Random(); final int bufferLength = 1024; final byte[] buffer = new byte[bufferLength]; random.nextBytes(buffer); String randomString = BaseEncoding.base64Url().omitPadding().encode(buffer); final String dockstoreAccessToken = Hashing.sha256() .hashString(githubLogin + randomString, Charsets.UTF_8).toString(); dockstoreToken = new Token(); dockstoreToken.setTokenSource(TokenType.DOCKSTORE.toString()); dockstoreToken.setContent(dockstoreAccessToken); dockstoreToken.setUserId(userID); dockstoreToken.setUsername(githubLogin); long dockstoreTokenId = tokenDAO.create(dockstoreToken); dockstoreToken = tokenDAO.findById(dockstoreTokenId); } else { userID = user.getId(); List<Token> tokens = tokenDAO.findDockstoreByUserId(userID); if (!tokens.isEmpty()) { dockstoreToken = tokens.get(0); } tokens = tokenDAO.findGithubByUserId(userID); if (!tokens.isEmpty()) { githubToken = tokens.get(0); } } if (dockstoreToken == null) { LOG.info("Could not find user's dockstore token. Making new one..."); final Random random = new Random(); final int bufferLength = 1024; final byte[] buffer = new byte[bufferLength]; random.nextBytes(buffer); String randomString = BaseEncoding.base64Url().omitPadding().encode(buffer); final String dockstoreAccessToken = Hashing.sha256() .hashString(githubLogin + randomString, Charsets.UTF_8).toString(); dockstoreToken = new Token(); dockstoreToken.setTokenSource(TokenType.DOCKSTORE.toString()); dockstoreToken.setContent(dockstoreAccessToken); dockstoreToken.setUserId(userID); dockstoreToken.setUsername(githubLogin); long dockstoreTokenId = tokenDAO.create(dockstoreToken); dockstoreToken = tokenDAO.findById(dockstoreTokenId); } if (githubToken == null) { LOG.info("Could not find user's github token. Making new one..."); // CREATE GITHUB TOKEN githubToken = new Token(); githubToken.setTokenSource(TokenType.GITHUB_COM.toString()); githubToken.setContent(accessToken); githubToken.setUserId(userID); githubToken.setUsername(githubLogin); tokenDAO.create(githubToken); LOG.info("Github token created for {}", githubLogin); } return dockstoreToken; }
From source file:org.hopestarter.wallet.ui.InputParser.java
public static PaymentIntent parsePaymentRequest(final byte[] serializedPaymentRequest) throws PaymentProtocolException { try {//from w w w. j a v a 2s .c o m if (serializedPaymentRequest.length > 50000) throw new PaymentProtocolException("payment request too big: " + serializedPaymentRequest.length); final Protos.PaymentRequest paymentRequest = Protos.PaymentRequest.parseFrom(serializedPaymentRequest); final String pkiName; final String pkiCaName; if (!"none".equals(paymentRequest.getPkiType())) { final KeyStore keystore = new TrustStoreLoader.DefaultTrustStoreLoader().getKeyStore(); final PkiVerificationData verificationData = PaymentProtocol.verifyPaymentRequestPki(paymentRequest, keystore); pkiName = verificationData.displayName; pkiCaName = verificationData.rootAuthorityName; } else { pkiName = null; pkiCaName = null; } final PaymentSession paymentSession = PaymentProtocol.parsePaymentRequest(paymentRequest); if (paymentSession.isExpired()) throw new PaymentProtocolException.Expired("payment details expired: current time " + new Date() + " after expiry time " + paymentSession.getExpires()); if (!paymentSession.getNetworkParameters().equals(Constants.NETWORK_PARAMETERS)) throw new PaymentProtocolException.InvalidNetwork( "cannot handle payment request network: " + paymentSession.getNetworkParameters()); final ArrayList<PaymentIntent.Output> outputs = new ArrayList<PaymentIntent.Output>(1); for (final PaymentProtocol.Output output : paymentSession.getOutputs()) outputs.add(PaymentIntent.Output.valueOf(output)); final String memo = paymentSession.getMemo(); final String paymentUrl = paymentSession.getPaymentUrl(); final byte[] merchantData = paymentSession.getMerchantData(); final byte[] paymentRequestHash = Hashing.sha256().hashBytes(serializedPaymentRequest).asBytes(); final PaymentIntent paymentIntent = new PaymentIntent(PaymentIntent.Standard.BIP70, pkiName, pkiCaName, outputs.toArray(new PaymentIntent.Output[0]), memo, paymentUrl, merchantData, null, paymentRequestHash); if (paymentIntent.hasPaymentUrl() && !paymentIntent.isSupportedPaymentUrl()) throw new PaymentProtocolException.InvalidPaymentURL( "cannot handle payment url: " + paymentIntent.paymentUrl); return paymentIntent; } catch (final InvalidProtocolBufferException x) { throw new PaymentProtocolException(x); } catch (final UninitializedMessageException x) { throw new PaymentProtocolException(x); } catch (final FileNotFoundException x) { throw new RuntimeException(x); } catch (final KeyStoreException x) { throw new RuntimeException(x); } }
From source file:zeitcoin.wallet.ui.InputParser.java
public static PaymentIntent parsePaymentRequest(@Nonnull final byte[] serializedPaymentRequest) throws PaymentProtocolException { try {//w w w . jav a 2 s .c om if (serializedPaymentRequest.length > 50000) throw new PaymentProtocolException("payment request too big: " + serializedPaymentRequest.length); final Protos.PaymentRequest paymentRequest = Protos.PaymentRequest.parseFrom(serializedPaymentRequest); final String pkiName; final String pkiCaName; if (!"none".equals(paymentRequest.getPkiType())) { final KeyStore keystore = new TrustStoreLoader.DefaultTrustStoreLoader().getKeyStore(); final PkiVerificationData verificationData = PaymentProtocol.verifyPaymentRequestPki(paymentRequest, keystore); pkiName = verificationData.displayName; pkiCaName = verificationData.rootAuthorityName; } else { pkiName = null; pkiCaName = null; } final PaymentSession paymentSession = PaymentProtocol.parsePaymentRequest(paymentRequest); if (paymentSession.isExpired()) throw new PaymentProtocolException.Expired("payment details expired: current time " + new Date() + " after expiry time " + paymentSession.getExpires()); if (!paymentSession.getNetworkParameters().equals(Constants.NETWORK_PARAMETERS)) throw new PaymentProtocolException.InvalidNetwork( "cannot handle payment request network: " + paymentSession.getNetworkParameters()); final ArrayList<PaymentIntent.Output> outputs = new ArrayList<PaymentIntent.Output>(1); for (final PaymentProtocol.Output output : paymentSession.getOutputs()) outputs.add(PaymentIntent.Output.valueOf(output)); final String memo = paymentSession.getMemo(); final String paymentUrl = paymentSession.getPaymentUrl(); final byte[] merchantData = paymentSession.getMerchantData(); final byte[] paymentRequestHash = Hashing.sha256().hashBytes(serializedPaymentRequest).asBytes(); final PaymentIntent paymentIntent = new PaymentIntent(PaymentIntent.Standard.BIP70, pkiName, pkiCaName, outputs.toArray(new PaymentIntent.Output[0]), memo, paymentUrl, merchantData, null, paymentRequestHash); if (paymentIntent.hasPaymentUrl() && !paymentIntent.isSupportedPaymentUrl()) throw new PaymentProtocolException.InvalidPaymentURL( "cannot handle payment url: " + paymentIntent.paymentUrl); return paymentIntent; } catch (final InvalidProtocolBufferException x) { throw new PaymentProtocolException(x); } catch (final UninitializedMessageException x) { throw new PaymentProtocolException(x); } catch (final FileNotFoundException x) { throw new RuntimeException(x); } catch (final KeyStoreException x) { throw new RuntimeException(x); } }
From source file:com.infinities.keystone4j.utils.Cms.java
public String hashToken(String tokenid, Algorithm mode) throws UnsupportedEncodingException, NoSuchAlgorithmException, DecoderException { if (mode == null) { mode = Algorithm.md5;/*from w w w. j a v a 2s. co m*/ } if (Strings.isNullOrEmpty(tokenid)) { throw new NullPointerException("invalid tokenid"); } if (isAsn1Token(tokenid) || isPkiz(tokenid)) { HashFunction hf = Hashing.md5(); if (mode == Algorithm.sha1) { hf = Hashing.sha1(); } else if (mode == Algorithm.sha256) { hf = Hashing.sha256(); } else if (mode == Algorithm.sha512) { hf = Hashing.sha512(); } HashCode hc = hf.newHasher().putString(tokenid).hash(); return toHex(hc.asBytes()); } else { return tokenid; } }
From source file:org.darkware.wpman.security.ChecksumDatabase.java
/** * Perform a checksum calculation on the given {@link ReadableByteChannel}. Other code should not create * implementations which are dependant on any particular characteristics of the checksum, but the checksum * is very likely to be based on a cryptographic-strength hash. The results of the checksum are encoded as * a base64 {@code String}./*from www. j a va2 s .c o m*/ * * @param channel The {@code ReadableByteChannel} to read data from. * @return A Base64 encoded {@code String} representing the checksum. * @throws IOException If there was an error while reading data from the channel. * @see Base64#encodeBase64String(byte[]) */ protected String doChecksum(ReadableByteChannel channel) throws IOException { Hasher hasher = Hashing.sha256().newHasher(); final ByteBuffer block = ByteBuffer.allocate(4096); while (channel.isOpen()) { int bytesRead = channel.read(block); if (bytesRead > 0) { block.flip(); hasher.putBytes(block.array(), 0, block.limit()); block.clear(); } else if (bytesRead == -1) { channel.close(); } } return Base64.encodeBase64String(hasher.hash().asBytes()); }
From source file:org.apache.servicecomb.serviceregistry.client.LocalServiceRegistryClientImpl.java
@Override public Holder<List<GetSchemaResponse>> getSchemas(String microserviceId) { Microservice microservice = microserviceIdMap.get(microserviceId); if (microservice == null) { throw new IllegalArgumentException("Invalid serviceId, serviceId=" + microserviceId); }//from w w w . j a v a 2s . c o m List<GetSchemaResponse> schemas = new ArrayList<>(); microservice.getSchemaMap().forEach((key, val) -> { GetSchemaResponse schema = new GetSchemaResponse(); schema.setSchema(val); schema.setSchemaId(key); schema.setSummary(Hashing.sha256().newHasher().putString(val, Charsets.UTF_8).hash().toString()); schemas.add(schema); }); Holder<List<GetSchemaResponse>> resultHolder = new Holder<>(); resultHolder.setStatusCode(Status.OK.getStatusCode()).setValue(schemas); return resultHolder; }