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

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

Introduction

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

Prototype

public static HashFunction sha256() 

Source Link

Document

Returns a hash function implementing the SHA-256 algorithm (256 hash bits) by delegating to the SHA-256 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 www. ja v  a2s  .  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:dpp.dbClasses.User.java

/**
 * return the generated encrypted password
 * @param password/*  w  ww  . j a v  a  2  s .  com*/
 * @return String
 */
private String encryptPassword(String password) {
    return Hashing.sha256().hashString(password, Charsets.UTF_8).toString();
}

From source file:io.atomix.primitive.partition.PartitionGroup.java

/**
 * Returns the partition for the given key.
 *
 * @param key the key for which to return the partition
 * @return the partition for the given key
 *//* w w  w  .jav a2 s .  c  om*/
default Partition getPartition(String key) {
    int hashCode = Hashing.sha256().hashString(key, StandardCharsets.UTF_8).asInt();
    return getPartition(getPartitionIds().get(Math.abs(hashCode) % getPartitionIds().size()));
}

From source file:org.onosproject.store.primitives.impl.FederatedDistributedPrimitiveCreator.java

@Override
public <K, V> AsyncConsistentMap<K, V> newAsyncConsistentMap(String name, Serializer serializer) {
    checkNotNull(name);/*from w  ww. java 2  s  .com*/
    checkNotNull(serializer);
    Map<PartitionId, AsyncConsistentMap<K, V>> maps = Maps.transformValues(members,
            partition -> partition.newAsyncConsistentMap(name, serializer));
    Hasher<K> hasher = key -> {
        int hashCode = Hashing.sha256().hashBytes(serializer.encode(key)).asInt();
        return sortedMemberPartitionIds.get(Math.abs(hashCode) % members.size());
    };
    return new PartitionedAsyncConsistentMap<>(name, maps, hasher);
}

From source file:org.jclouds.glacier.util.TreeHash.java

/**
 * Builds the Hash and the TreeHash values of the payload.
 *
 * @return The calculated TreeHash./*  w  w  w  .j av  a 2s . c o  m*/
 * @see <a href="http://docs.aws.amazon.com/amazonglacier/latest/dev/checksum-calculations.html" />
 */
public static TreeHash buildTreeHashFromPayload(Payload payload) throws IOException {
    InputStream is = null;
    try {
        is = checkNotNull(payload, "payload").openStream();
        Builder<HashCode> list = ImmutableList.builder();
        HashingInputStream linearHis = new HashingInputStream(Hashing.sha256(), is);
        while (true) {
            HashingInputStream chunkedHis = new HashingInputStream(Hashing.sha256(),
                    ByteStreams.limit(linearHis, CHUNK_SIZE));
            long count = ByteStreams.copy(chunkedHis, ByteStreams.nullOutputStream());
            if (count == 0) {
                break;
            }
            list.add(chunkedHis.hash());
        }
        //The result list contains exactly one element now.
        return new TreeHash(hashList(list.build()), linearHis.hash());
    } finally {
        closeQuietly(is);
    }
}

From source file:com.ea.promed.beans.ClientBean.java

public String createClient() throws MessagingException, UnsupportedEncodingException {

    String hash = Hashing.sha256().hashString(client.getUser().getPassword(), Charsets.UTF_8).toString();

    client.getUser().setVerification(hash);
    client.getUser().setPassword(hash);/*from  w  w  w .j ava2 s . c  o  m*/
    clientFacade.create(client);

    emailBean.setToemail(client.getUser().getEmail());
    emailBean.setSubject("Email Verification from Pro Medical Services");
    emailBean.setMessagetext(client.getFirstName(), hash);

    emailBean.sendEMail();

    sessionMap.put("message", "Registration successfull. Please check your email to verify");

    return "dashboard/index?faces-redirect=true";
}

From source file:org.dcache.util.CachingCertificateValidator.java

@Override
public ValidationResult validate(final X509Certificate[] certChain) {
    checkNotNull(certChain, "Cannot validate a null cert chain.");
    checkArgument(certChain.length > 0, "Cannot validate a cert chain of length 0.");

    int pos = 0;/* ww  w .  ja  v a  2  s. com*/
    try {
        /* Check that the chain is still valid; would be nice if we instead could limit the lifetime of the cache
         * entry, but Guava doesn't allow us to do that.
         */
        Hasher hasher = Hashing.sha256().newHasher();
        for (X509Certificate cert : certChain) {
            cert.checkValidity();
            hasher.putBytes(cert.getEncoded());
            pos++;
        }

        String certFingerprint = hasher.hash().toString();

        return cache.get(certFingerprint, () -> validator.validate(certChain));
    } catch (CertificateEncodingException e) {
        return new ValidationResult(false, singletonList(
                new ValidationError(certChain, pos, ValidationErrorCode.inputError, e.getMessage())));
    } catch (ExecutionException e) {
        return new ValidationResult(false, singletonList(
                new ValidationError(certChain, pos, ValidationErrorCode.inputError, e.getMessage())));
    } catch (CertificateExpiredException e) {
        return new ValidationResult(false, singletonList(
                new ValidationError(certChain, pos, ValidationErrorCode.certificateExpired, e.getMessage())));
    } catch (CertificateNotYetValidException e) {
        return new ValidationResult(false, singletonList(new ValidationError(certChain, pos,
                ValidationErrorCode.certificateNotYetValid, e.getMessage())));
    }
}

From source file:org.graylog2.plugin.system.NodeId.java

/**
 * Generate an "anonymized" node ID for use with external services. Currently it just hashes the actual node ID
 * using SHA-256.//  w  ww .j  a va 2 s .c  o  m
 *
 * @return The anonymized ID derived from hashing the node ID.
 */
public String anonymize() {
    return Hashing.sha256().hashString(id, StandardCharsets.UTF_8).toString();
}

From source file:org.apache.beam.runners.core.construction.PipelineResources.java

private static String calculateDirectoryContentHash(File directoryToStage) {
    Hasher hasher = Hashing.sha256().newHasher();
    try (OutputStream hashStream = Funnels.asOutputStream(hasher)) {
        ZipFiles.zipDirectory(directoryToStage, hashStream);
        return hasher.hash().toString();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }//from   ww  w . j  a v a 2 s . c o m
}

From source file:Expenses.Users.java

public void setPassword(String password) {
    String hash = Hashing.sha256().hashString(password, Charsets.UTF_8).toString();
    this.password = hash;
}