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:ph.samson.maven.enforcer.rule.checksum.FileChecksum.java

@Override
public void execute(EnforcerRuleHelper erh) throws EnforcerRuleException {
    if (file == null || !file.canRead()) {
        throw new EnforcerRuleException("Missing file: " + file);
    }//from  w ww.j av a 2 s. c  om

    HashFunction hashFn;
    switch (type) {
    case "crc32":
        hashFn = Hashing.crc32();
        break;
    case "crc32c":
        hashFn = Hashing.crc32c();
        break;
    case "md5":
        hashFn = Hashing.md5();
        break;
    case "sha1":
        hashFn = Hashing.sha1();
        break;
    case "sha256":
        hashFn = Hashing.sha256();
        break;
    case "sha512":
        hashFn = Hashing.sha512();
        break;
    default:
        throw new EnforcerRuleException("Unsupported hash type: " + type);
    }

    String hash;
    try {
        hash = hashFn.hashBytes(Files.readAllBytes(file.toPath())).toString();
    } catch (IOException ex) {
        throw new EnforcerRuleException("Failed reading " + file, ex);
    }

    if (!hash.equalsIgnoreCase(checksum)) {
        throw new EnforcerRuleException(
                type + " hash of " + file + " was " + hash + " but expected " + checksum);
    }
}

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

@Override
public Sha1HashCode computeSha1(Path pathRelativeToProjectRootOrJustAbsolute) throws IOException {
    Path fileToHash = getPathForRelativePath(pathRelativeToProjectRootOrJustAbsolute);
    try {// ww w  . j ava2 s .c o  m
        // 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
            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);

    } catch (IOException e) {
        String msg = String.format("Error computing Sha1 for %s: %s", fileToHash.toString(), e.getMessage());

        throw new IOException(msg, e);
    }
}

From source file:org.apache.james.user.jpa.model.JPAUser.java

@SuppressWarnings("deprecation")
private static HashFunction chooseHashing(String algorithm) {
    switch (algorithm) {
    case "MD5":
        return Hashing.md5();
    case "SHA-256":
        return Hashing.sha256();
    case "SHA-512":
        return Hashing.sha512();
    default:// w w w. j a v  a2s .  co m
        return Hashing.sha1();
    }
}

From source file:com.github.mgunlogson.cuckoofilter4j.SerializableSaltedHasher.java

private static HashFunction configureHash(Algorithm alg, long seedNSalt, long addlSipSeed) {
    switch (alg) {
    case xxHash64:
        return new xxHashFunction(seedNSalt);
    case Murmur3_128:
        return Hashing.murmur3_128((int) seedNSalt);
    case Murmur3_32:
        return Hashing.murmur3_32((int) seedNSalt);
    case sha256:/*from   w  w  w. ja  v a 2 s  .  c om*/
        return Hashing.sha1();
    case sipHash24:
        return Hashing.sipHash24(seedNSalt, addlSipSeed);
    default:
        throw new IllegalArgumentException("Invalid Enum Hashing Algorithm???");
    }
}

From source file:com.facebook.buck.rules.RuleKeyBuilder.java

public RuleKeyBuilder(SourcePathResolver resolver, FileHashCache hashCache,
        RuleKeyBuilderFactory defaultRuleKeyBuilderFactory) {
    this.resolver = resolver;
    this.hasher = new AppendingHasher(Hashing.sha1(), /* numHashers */ 2);
    this.hashCache = hashCache;
    this.defaultRuleKeyBuilderFactory = defaultRuleKeyBuilderFactory;
    this.keyStack = new Stack<>();
    if (logger.isVerboseEnabled()) {
        this.logElms = Lists.newArrayList();
    }//from   ww w. java 2 s .co m
}

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

/**
 * Returns the hash of the license text, used for persisting acceptance. Never null.
 *///from  w w  w.j a  va 2 s .c  o  m
@NonNull
public String getLicenseHash() {
    return Hashing.sha1().hashBytes(getValue().getBytes()).toString();
}

From source file:org.glowroot.agent.central.SharedQueryTextLimiter.java

Trace.SharedQueryText buildTraceSharedQueryText(String fullText, List<String> fullTextSha1s) {
    if (fullText.length() > 2 * Constants.TRACE_QUERY_TEXT_TRUNCATE) {
        String fullTextSha1 = Hashing.sha1().hashString(fullText, UTF_8).toString();
        if (sentInThePastDay.getIfPresent(fullTextSha1) == null) {
            fullTextSha1s.add(fullTextSha1);
            // need to send full text
            return Trace.SharedQueryText.newBuilder().setFullText(fullText).build();
        } else {/* ww w . j  a v  a 2s .  c o m*/
            // ok to just send truncated text
            return Trace.SharedQueryText.newBuilder()
                    .setTruncatedText(fullText.substring(0, Constants.TRACE_QUERY_TEXT_TRUNCATE))
                    .setTruncatedEndText(fullText.substring(
                            fullText.length() - Constants.TRACE_QUERY_TEXT_TRUNCATE, fullText.length()))
                    .setFullTextSha1(fullTextSha1).build();
        }
    } else {
        return Trace.SharedQueryText.newBuilder().setFullText(fullText).build();
    }
}

From source file:com.android.builder.files.FileCacheByPath.java

/**
 * Computes a unique key identifying the path of the file.
 *
 * @param f the path/*from w w  w  .j  a  v  a 2s .com*/
 * @return the unique key
 */
@NonNull
private static String key(@NonNull File f) {
    String absolutePath = f.getAbsolutePath();
    byte[] sha1Sum = Hashing.sha1().hashString(absolutePath, Charsets.UTF_8).asBytes();
    return new String(Base64.encodeBase64(sha1Sum), Charsets.US_ASCII).replaceAll("/", "_");
}

From source file:net.yoomai.wechat.utils.StringUtils.java

/**
 * ????/*from  www .  j av a2 s .  c om*/
 *
 * @param params  ?ASCII ????
 * @param encrypt ? SHA1 MD5
 * @return
 */
public static String signature(Map params, String encrypt, boolean toUpperCase) {
    String sign = "";
    // ?
    String buffer = generateQueryString(params, true);

    // log.debug(" => {}", buffer.toString());
    if ("MD5".equals(encrypt)) {
        // MD5
        sign = Hashing.md5().hashString(buffer, Charsets.UTF_8).toString();
    } else if ("SHA1".equals(encrypt)) {
        // SHA1
        sign = Hashing.sha1().hashString(buffer, Charsets.UTF_8).toString();
    }
    // log.debug("? <=> {}", sign);

    if (toUpperCase) {
        sign = sign.toUpperCase();
    }

    return sign;
}

From source file:com.facebook.buck.rules.OutputKey.java

/**
 * Sentinel OutputKeys are output as a string of 's' characters, and non-idempotent OutputKeys are
 * normally output as a string of 'x' characters, but when comparing two sets of OutputKeys in
 * textual form it is necessary to mangle one of the two sets, so that non-idempotent OutputKeys
 * are never considered equal.//  w w  w.  j  a  v a2s.  c o m
 */
public String toString(boolean mangleNonIdempotent) {
    if (isSentinel() || !isIdempotent()) {
        String replacementChar = isSentinel() ? "s" : (!mangleNonIdempotent ? "x" : "y");
        return new String(new char[Hashing.sha1().bits() / 4]).replace("\0", replacementChar);
    }
    return hashCode.toString();
}