Example usage for com.google.common.hash Hashing sha1

List of usage examples for com.google.common.hash Hashing sha1

Introduction

In this page you can find the example usage for com.google.common.hash Hashing sha1.

Prototype

public static HashFunction sha1() 

Source Link

Document

Returns a hash function implementing the SHA-1 algorithm (160 hash bits) by delegating to the SHA-1 MessageDigest .

Usage

From source file:com.facebook.buck.util.DefaultFileHashCache.java

public DefaultFileHashCache(ProjectFilesystem projectFilesystem, Console console) {
    this.projectFilesystem = Preconditions.checkNotNull(projectFilesystem);
    this.console = Preconditions.checkNotNull(console);

    this.loadingCache = CacheBuilder.newBuilder().build(new CacheLoader<Path, HashCode>() {
        @Override//from  w  w w .j a v  a2 s.c  o  m
        public HashCode load(Path path) throws Exception {
            File file = DefaultFileHashCache.this.projectFilesystem.resolve(path).toFile();
            InputSupplier<? extends InputStream> inputSupplier = Files.newInputStreamSupplier(file);
            return ByteStreams.hash(inputSupplier, Hashing.sha1());
        }
    });
}

From source file:org.obm.push.impl.ClientIdServiceImpl.java

@Override
public String hash(UserDataRequest udr, String clientId) {
    return Hashing.sha1().newHasher().putUnencodedChars(udr.getCredentials().getUser().getLoginAtDomain())
            .putUnencodedChars(udr.getDevType()).putUnencodedChars(clientId).hash().toString();
}

From source file:com.facebook.buck.file.DownloadStep.java

@Override
public StepExecutionResult execute(ExecutionContext context) throws InterruptedException {
    BuckEventBus eventBus = context.getBuckEventBus();
    try {// w  ww . ja v a 2  s.co  m
        Path resolved = filesystem.resolve(output);
        boolean success = downloader.fetch(eventBus, url, resolved);

        if (!success) {
            return StepExecutionResult.of(reportFailedDownload(eventBus));
        }

        HashCode readHash = Files.asByteSource(resolved.toFile()).hash(Hashing.sha1());
        if (!sha1.equals(readHash)) {
            eventBus.post(ConsoleEvent.severe(
                    "Unable to download %s (hashes do not match. Expected %s, saw %s)", url, sha1, readHash));
            return StepExecutionResult.of(-1);
        }
    } catch (IOException e) {
        return StepExecutionResult.of(reportFailedDownload(eventBus));
    } catch (HumanReadableException e) {
        eventBus.post(ConsoleEvent.severe(e.getHumanReadableErrorMessage(), e));
        return StepExecutionResult.of(-1);
    }

    return StepExecutionResult.SUCCESS;
}

From source file:com.spotify.crtauth.Fingerprint.java

/**
 * Calculate a bytes from the provided public key.
 * @param publicKey the RSAPublicKey instance to make this fingerprint match
 *//* w  w w. ja v  a 2  s.c  o m*/
public Fingerprint(RSAPublicKey publicKey) {
    byte[] digestBytes = Hashing.sha1().hashBytes(getDerEncoding(publicKey)).asBytes();
    checkPositionIndex(FINGERPRINT_LENGTH, digestBytes.length);
    this.bytes = Arrays.copyOf(digestBytes, FINGERPRINT_LENGTH);
}

From source file:org.gradle.api.internal.artifacts.repositories.resolver.DefaultExternalResourceAccessor.java

private LocallyAvailableExternalResource resolve(ExternalResourceName resource, URI uri) {
    LOGGER.debug("Loading {}", resource);

    try {/*from  w  w w.  j av  a2 s.c o m*/
        final String key = Hashing.sha1().hashString(uri.toASCIIString(), Charsets.UTF_8).toString();
        return resourceAccessor.getResource(resource,
                new CacheAwareExternalResourceAccessor.ResourceFileStore() {
                    public LocallyAvailableResource moveIntoCache(File downloadedResource) {
                        return fileStore.move(key, downloadedResource);
                    }
                }, null);
    } catch (Exception e) {
        throw ResourceExceptions.getFailed(uri, e);
    }
}

From source file:com.facebook.buck.io.DefaultProjectFilesystemDelegate.java

@Override
public Sha1HashCode computeSha1(Path pathRelativeToProjectRootOrJustAbsolute) throws IOException {
    final Path fileToHash = getPathForRelativePath(pathRelativeToProjectRootOrJustAbsolute);

    // Normally, we would just use `Files.hash(fileToHash.toFile(), Hashing.sha1())`, but if
    // fileToHash is backed by Jimfs, its toFile() method throws an UnsupportedOperationException.
    // Creating the input stream via java.nio.file.Files.newInputStream() avoids this issue.
    ByteSource source = new ByteSource() {
        @Override/*  www  .j a va  2s  .  co m*/
        public InputStream openStream() throws IOException {
            // No need to wrap with BufferedInputStream because ByteSource uses ByteStreams.copy(),
            // which already buffers.
            return Files.newInputStream(fileToHash);
        }
    };
    HashCode hashCode = source.hash(Hashing.sha1());
    return Sha1HashCode.fromHashCode(hashCode);
}

From source file:com.android.repository.api.Downloader.java

/**
 * Hash the given input stream./*from  www  . j  a va  2  s. c  o  m*/
 * @param in The stream to hash. It will be fully consumed but not closed.
 * @param fileSize The expected length of the stream, for progress display purposes.
 * @param progress The indicator will be updated with the expected completion fraction.
 * @return The sha1 hash of the input stream.
 * @throws IOException IF there's a problem reading from the stream.
 */
@VisibleForTesting
@NonNull
static String hash(@NonNull InputStream in, long fileSize, @NonNull ProgressIndicator progress)
        throws IOException {
    progress.setText("Checking existing file...");
    Hasher sha1 = Hashing.sha1().newHasher();
    byte[] buf = new byte[5120];
    long totalRead = 0;
    int bytesRead;
    while ((bytesRead = in.read(buf)) > 0) {
        sha1.putBytes(buf, 0, bytesRead);
        progress.setFraction((double) totalRead / (double) fileSize);
    }
    return sha1.hash().toString();
}

From source file:co.indexia.antiquity.graph.ElementUtils.java

/**
 * <p>/*ww  w.  j a  v a 2 s  .c  o  m*/
 * Calculate the private hash of an {@link Element}.
 * </p>
 * 
 * <p>
 * The private hash contains only the properties of the {@link Element},
 * without its associated elements.
 * </p>
 * 
 * <p>
 * The hash is calculated based on SHA1 algorithm
 * </p>
 * 
 * TODO Handle arrays values properly.
 * 
 * @param element The element to calculate the private hash for.
 * @param excludedKeys the keys to exclude when hash is calculated.
 * @return A string representation of the hash
 * @see HashCode#toString()
 */
public static String calculateElementPrivateHash(Element element, Set<String> excludedKeys) {
    Map<String, Object> props = ElementUtils.getPropertiesAsMap(element, excludedKeys);
    Joiner.MapJoiner propsJoiner = Joiner.on('&').withKeyValueSeparator("=");

    HashFunction hf = Hashing.sha1();
    Hasher h = hf.newHasher();

    //h.putString("[" + element.getId().toString() + "]");
    h.putString(propsJoiner.join(props), Charset.defaultCharset());

    return h.hash().toString();
}

From source file:org.apache.beam.sdk.io.hadoop.inputformat.hashing.HashingFn.java

@Override
public Accum addInput(Accum accum, String input) {
    List<HashCode> elementHashes = Lists.newArrayList();
    if (accum.hashCode != null) {
        elementHashes.add(accum.hashCode);
    }// w w  w .  j  av a2  s  .c  om
    HashCode inputHashCode = Hashing.sha1().hashString(input, StandardCharsets.UTF_8);
    elementHashes.add(inputHashCode);
    accum.hashCode = Hashing.combineUnordered(elementHashes);
    return accum;
}

From source file:com.facebook.buck.js.JsFlavors.java

public static Flavor fileFlavorForSourcePath(final Path path) {
    final String hash = Hashing.sha1().hashString(MorePaths.pathWithUnixSeparators(path), Charsets.UTF_8)
            .toString().substring(0, 10);
    final String safeFileName = Flavor.replaceInvalidCharacters(path.getFileName().toString());
    return InternalFlavor.of(fileFlavorPrefix + safeFileName + "-" + hash);
}