List of usage examples for com.google.common.hash Hashing sha256
public static HashFunction sha256()
From source file:org.graylog2.web.resources.WebInterfaceAssetsResource.java
private Response getResponse(Request request, String filename, URL resourceUrl, boolean fromPlugin) throws IOException, URISyntaxException { final Date lastModified; final InputStream stream; final HashCode hashCode; switch (resourceUrl.getProtocol()) { case "file": { final File file = new File(resourceUrl.toURI()); lastModified = new Date(file.lastModified()); stream = new FileInputStream(file); hashCode = Files.hash(file, Hashing.sha256()); break;//from ww w . j ava 2s.c o m } case "jar": { final URI uri = resourceUrl.toURI(); final FileSystem fileSystem = fileSystemCache.getUnchecked(uri); final java.nio.file.Path path = fileSystem.getPath(pluginPrefixFilename(fromPlugin, filename)); final FileTime lastModifiedTime = java.nio.file.Files.getLastModifiedTime(path); lastModified = new Date(lastModifiedTime.toMillis()); stream = resourceUrl.openStream(); hashCode = Resources.asByteSource(resourceUrl).hash(Hashing.sha256()); break; } default: throw new IllegalArgumentException("Not a jar or file"); } final EntityTag entityTag = new EntityTag(hashCode.toString()); final Response.ResponseBuilder response = request.evaluatePreconditions(lastModified, entityTag); if (response != null) { return response.build(); } final String contentType = firstNonNull(mimeTypes.getContentType(filename), MediaType.APPLICATION_OCTET_STREAM); final CacheControl cacheControl = new CacheControl(); cacheControl.setMaxAge((int) TimeUnit.DAYS.toSeconds(365)); cacheControl.setNoCache(false); cacheControl.setPrivate(false); return Response.ok(stream).header(HttpHeaders.CONTENT_TYPE, contentType).tag(entityTag) .cacheControl(cacheControl).lastModified(lastModified).build(); }
From source file:com.cinchapi.common.io.Files.java
/** * Get a consistent file path that represents the hash for the specified * {@code key}./*from www . j av a2s . co m*/ * <p> * This method does <strong>NOT</strong> create a file at the returned path, * or any of the parent directories. * </p> * * @param key the key to hash * @return the hashed file path */ public static Path getHashedFilePath(String key) { String hash = Hashing.sha256().hashString(key, StandardCharsets.UTF_8).toString(); ArrayBuilder<String> array = ArrayBuilder.builder(); array.add(".hash"); StringBuilder sb = new StringBuilder(); char[] chars = hash.toCharArray(); for (int i = 0; i < chars.length; ++i) { char c = chars[i]; sb.append(c); if (i >= 4 && i % 4 == 0) { array.add(sb.toString()); sb.setLength(0); } } return Paths.get(USER_HOME, array.build()); }
From source file:strat.mining.stratum.proxy.utils.mining.SHA256HashingUtils.java
/** * Apply a single sha256 round over the given data. * /*from w w w .ja v a 2 s .com*/ * @param data * @return */ public static final byte[] sha256Hash(byte[] data) { HashCode hashBytes = Hashing.sha256().hashBytes(data); return hashBytes.asBytes(); }
From source file:com.matthewmitchell.peercoinj.core.CheckpointManager.java
private Sha256Hash readTextual(InputStream inputStream) throws IOException { Hasher hasher = Hashing.sha256().newHasher(); BufferedReader reader = null; try {/* ww w .j a v a 2 s . c o m*/ reader = new BufferedReader(new InputStreamReader(inputStream, Charsets.US_ASCII)); String magic = reader.readLine(); if (!TEXTUAL_MAGIC.equals(magic)) throw new IOException("unexpected magic: " + magic); int numSigs = Integer.parseInt(reader.readLine()); for (int i = 0; i < numSigs; i++) reader.readLine(); // Skip sigs for now. int numCheckpoints = Integer.parseInt(reader.readLine()); checkState(numCheckpoints > 0); // Hash numCheckpoints in a way compatible to the binary format. hasher.putBytes(ByteBuffer.allocate(4).order(ByteOrder.BIG_ENDIAN).putInt(numCheckpoints).array()); final int size = StoredBlock.COMPACT_SERIALIZED_SIZE; ByteBuffer buffer = ByteBuffer.allocate(size); for (int i = 0; i < numCheckpoints; i++) { byte[] bytes = BASE64.decode(reader.readLine()); hasher.putBytes(bytes); buffer.position(0); buffer.put(bytes); buffer.position(0); StoredBlock block = StoredBlock.deserializeCompact(params, buffer); checkpoints.put(block.getHeader().getTimeSeconds(), block); } HashCode hash = hasher.hash(); log.info("Read {} checkpoints, hash is {}", checkpoints.size(), hash); return new Sha256Hash(hash.asBytes()); } finally { if (reader != null) reader.close(); } }
From source file:org.apache.beam.runners.fnexecution.artifact.BeamFileSystemArtifactStagingService.java
private String encodedFileName(ArtifactMetadata artifactMetadata) { return "artifact_" + Hashing.sha256().hashString(artifactMetadata.getName(), CHARSET).toString(); }
From source file:com.google.devtools.kythe.extractors.java.standalone.AbstractJavacWrapper.java
protected static String createTargetFromSourceFiles(List<String> sourceFiles) { List<String> sortedSourceFiles = Lists.newArrayList(sourceFiles); Collections.sort(sortedSourceFiles); String joinedSourceFiles = Joiner.on(":").join(sortedSourceFiles); return "#" + Hashing.sha256().hashUnencodedChars(joinedSourceFiles).toString(); }
From source file:com.hubrick.vertx.s3.signature.AWS4SignatureBuilder.java
public AWS4SignatureBuilder payload(final byte[] payload) { Preconditions.checkNotNull(payload, "payload must not be null"); this.payloadHash = Hashing.sha256().hashBytes(payload).toString(); return this; }
From source file:io.bazel.rules.closure.webfiles.WebfilesWriter.java
/** * Adds {@code webfile} {@code data} to zip archive and returns proto index entry. * * <p>The returned value can be written to the manifest associated with a rule so that parent * rules can obtain the data written here. * * @param webfile original information about webfile * @return modified version of {@code webfile} that's suitable for writing to the final manifest *//* ww w . j ava2 s .co m*/ public WebfileInfo writeWebfile(WebfileInfo webfile, @WillNotClose InputStream input) throws IOException { checkNotNull(input, "input"); String name = WebfilesUtils.getZipEntryName(webfile); createEntriesForParentDirectories(name); ZipEntry entry = new ZipEntry(name); entry.setComment(webfile.getRunpath()); // Build outputs need to be deterministic. Bazel also doesn't care about modified times because // it uses the file digest to determine if a file is invalidated. So even if we did copy the // time information from the original file, it still might not be a good idea. entry.setCreationTime(EPOCH); entry.setLastModifiedTime(EPOCH); entry.setLastAccessTime(EPOCH); if (isAlreadyCompressed(webfile.getWebpath())) { // When opting out of compression, ZipOutputStream expects us to do ALL THIS entry.setMethod(ZipEntry.STORED); if (input instanceof ByteArrayInputStream) { entry.setSize(input.available()); Hasher hasher = Hashing.crc32().newHasher(); input.mark(-1); ByteStreams.copy(input, Funnels.asOutputStream(hasher)); input.reset(); entry.setCrc(hasher.hash().padToLong()); } else { byte[] data = ByteStreams.toByteArray(input); entry.setSize(data.length); entry.setCrc(Hashing.crc32().hashBytes(data).padToLong()); input = new ByteArrayInputStream(data); } } else { entry.setMethod(ZipEntry.DEFLATED); } HasherInputStream source = new HasherInputStream(input, Hashing.sha256().newHasher()); long offset = channel.position(); zip.putNextEntry(entry); ByteStreams.copy(source, zip); zip.closeEntry(); buffer.flush(); WebfileInfo result = webfile.toBuilder().clearPath() // Now that it's in the zip, we don't need the ctx.action execroot path. .setInZip(true).setOffset(offset).setDigest(ByteString.copyFrom(source.hasher.hash().asBytes())) .build(); webfiles.add(result); return result; }
From source file:org.guldenj.core.CheckpointManager.java
private Sha256Hash readTextual(InputStream inputStream) throws IOException { Hasher hasher = Hashing.sha256().newHasher(); BufferedReader reader = null; try {/*ww w .j av a2 s. co m*/ reader = new BufferedReader(new InputStreamReader(inputStream, Charsets.US_ASCII)); String magic = reader.readLine(); if (!TEXTUAL_MAGIC.equals(magic)) throw new IOException("unexpected magic: " + magic); int numSigs = Integer.parseInt(reader.readLine()); for (int i = 0; i < numSigs; i++) reader.readLine(); // Skip sigs for now. int numCheckpoints = Integer.parseInt(reader.readLine()); checkState(numCheckpoints > 0); // Hash numCheckpoints in a way compatible to the binary format. hasher.putBytes(ByteBuffer.allocate(4).order(ByteOrder.BIG_ENDIAN).putInt(numCheckpoints).array()); final int size = StoredBlock.COMPACT_SERIALIZED_SIZE; ByteBuffer buffer = ByteBuffer.allocate(size); for (int i = 0; i < numCheckpoints; i++) { byte[] bytes = BASE64.decode(reader.readLine()); hasher.putBytes(bytes); buffer.position(0); buffer.put(bytes); buffer.position(0); StoredBlock block = StoredBlock.deserializeCompact(params, buffer); checkpoints.put(block.getHeader().getTimeSeconds(), block); } HashCode hash = hasher.hash(); log.info("Read {} checkpoints, hash is {}", checkpoints.size(), hash); return Sha256Hash.wrap(hash.asBytes()); } finally { if (reader != null) reader.close(); } }
From source file:org.haiku.haikudepotserver.dataobjects.User.java
/** * <p>This method will configure a random salt value.</p> *///from www . j av a 2 s. co m public void setPasswordSalt() { String randomHash = Hashing.sha256().hashUnencodedChars(UUID.randomUUID().toString()).toString(); setPasswordSalt(randomHash.substring(0, 16)); // LDAP server doesn't seem to like very long salts }