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:com.globo.galeb.consistenthash.HashAlgorithm.java

/**
 * Calc Hash./*from   w ww  . j  a v  a  2s.  c  o m*/
 *
 * @param key the key
 * @return int hash
 */
public HashAlgorithm hash(Object key) {
    HashFunction hashAlgorithm;
    switch (hashType) {
    case MD5:
        hashAlgorithm = Hashing.md5();
        break;
    case MURMUR3_32:
        hashAlgorithm = Hashing.murmur3_32();
        break;
    case SHA256:
        hashAlgorithm = Hashing.sha256();
        break;
    case SIP24:
        hashAlgorithm = Hashing.sipHash24();
        break;
    default:
        hashAlgorithm = Hashing.sipHash24();
        break;
    }
    if (key instanceof String) {
        hashCode = hashAlgorithm.newHasher().putString((String) key, Charsets.UTF_8).hash();
    } else if (key instanceof Long) {
        hashCode = hashAlgorithm.newHasher().putLong((Long) key).hash();
    } else {
        hashCode = hashAlgorithm.newHasher().hash();
    }
    return this;
}

From source file:com.facebook.presto.ml.ModelUtils.java

/**
 * Serializes the model using the following format
 * int: format version//  w ww. j  ava  2 s.co  m
 * byte[32]: SHA256 hash of all following data
 * int: id of algorithm
 * int: length of hyperparameters section
 * byte[]: hyperparameters (currently not used)
 * long: length of data section
 * byte[]: model data
 *
 * note: all multibyte values are in little endian
 */
public static Slice serialize(Model model) {
    requireNonNull(model, "model is null");
    Integer id = MODEL_SERIALIZATION_IDS.get(model.getClass());
    requireNonNull(id, "id is null");
    int size = HYPERPARAMETERS_OFFSET;

    // hyperparameters aren't implemented yet
    byte[] hyperparameters = new byte[0];
    size += hyperparameters.length;

    int dataLengthOffset = size;
    size += SIZE_OF_LONG;
    int dataOffset = size;
    byte[] data = model.getSerializedData();
    size += data.length;

    Slice slice = Slices.allocate(size);
    slice.setInt(VERSION_OFFSET, CURRENT_FORMAT_VERSION);
    slice.setInt(ALGORITHM_OFFSET, id);
    slice.setInt(HYPERPARAMETER_LENGTH_OFFSET, hyperparameters.length);
    slice.setBytes(HYPERPARAMETERS_OFFSET, hyperparameters);
    slice.setLong(dataLengthOffset, data.length);
    slice.setBytes(dataOffset, data);

    byte[] modelHash = Hashing.sha256()
            .hashBytes(slice.getBytes(ALGORITHM_OFFSET, slice.length() - ALGORITHM_OFFSET)).asBytes();
    checkState(modelHash.length == 32, "sha256 hash code expected to be 32 bytes");
    slice.setBytes(HASH_OFFSET, modelHash);

    return slice;
}

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

public String resetPassword() throws IOException {

    User cUser = (User) sessionMap.get("cUser");
    String code = cUser.getVerification();

    if (user.getPassword().equals(getVerifyPassword())) {

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

        cUser.setPassword(hash);/*from w  ww . j  a  v a2  s  . c  o  m*/
        cUser.setVerification("");

        userFacade.edit(cUser);

        sessionMap.put("message",
                "Password Updated successfully. Please login with your new username and password.");

        System.out.println("password changed");

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

    } else {
        sessionMap.put("message", "Password Not Matched.");
    }

    return "reset-password?faces-redirect=true&code=" + code;

}

From source file:org.apache.rya.indexing.pcj.fluo.app.query.StatementPatternIdManager.java

/**
 * Remove specified Set of ids from the Fluo table and updates the entry with Column
 * {@link FluoQueryColumns#STATEMENT_PATTERN_IDS}. Also updates the hash of the updated nodeId Set and writes that
 * to the Column {@link FluoQueryColumns#STATEMENT_PATTERN_IDS_HASH}
 *
 * @param tx - Fluo Transaction object for performing atomic operations on Fluo table.
 * @param ids - ids to remove from the StatementPattern nodeId Set
 *//*from www  .ja va  2  s . c o  m*/
public static void removeStatementPatternIds(TransactionBase tx, Set<String> ids) {
    checkNotNull(tx);
    checkNotNull(ids);
    Optional<Bytes> val = Optional.fromNullable(tx.get(Bytes.of(STATEMENT_PATTERN_ID), STATEMENT_PATTERN_IDS));
    Set<String> storedIds = new HashSet<>();
    if (val.isPresent()) {
        storedIds = Sets.newHashSet(val.get().toString().split(VAR_DELIM));
    }
    storedIds.removeAll(ids);
    String idString = Joiner.on(VAR_DELIM).join(ids);
    tx.set(Bytes.of(STATEMENT_PATTERN_ID), STATEMENT_PATTERN_IDS, Bytes.of(idString));
    tx.set(Bytes.of(STATEMENT_PATTERN_ID), STATEMENT_PATTERN_IDS_HASH,
            Bytes.of(Hashing.sha256().hashString(idString).toString()));
}

From source file:sockslib.server.manager.HashPasswordProtector.java

private Hasher chooseHasher(HashAlgorithm algorithm) {
    Hasher hasher = null;//from  w  w  w .  j a  v a2 s.  co m
    switch (algorithm) {

    case MD5:
        hasher = Hashing.md5().newHasher();
        break;
    case SHA1:
        hasher = Hashing.sha1().newHasher();
        break;
    case SHA256:
        hasher = Hashing.sha256().newHasher();
        break;
    case SHA512:
        hasher = Hashing.sha512().newHasher();
        break;

    }
    return hasher;
}

From source file:org.hawkular.metrics.api.jaxrs.filter.AdminFilter.java

private boolean validAdminToken(String adminToken) {
    if (savedAdminToken == null) {
        savedAdminToken = configurationService.load("org.hawkular.metrics", "admin.token").toBlocking()
                .firstOrDefault("");
    }/*from w w  w. j a  v  a  2  s.c  o  m*/

    adminToken = Hashing.sha256().newHasher().putString(adminToken, Charsets.UTF_8).hash().toString();

    if (adminToken.equals(savedAdminToken)) {
        return true;
    }

    return false;
}

From source file:org.apache.jackrabbit.oak.plugins.memory.AbstractBlob.java

private synchronized HashCode getSha256() {
    // Blobs are immutable so we can safely cache the hash
    if (hashCode == null) {
        try {/*w w  w.j  a v  a2s . c  o m*/
            hashCode = ByteStreams.hash(supplier(this), Hashing.sha256());
        } catch (IOException e) {
            throw new IllegalStateException("Hash calculation failed", e);
        }
    }
    return hashCode;
}

From source file:com.facebook.buck.parser.cache.impl.Fingerprinter.java

/**
 * Calculates a strong fingerprint./*from   w  w  w  . ja  v a2  s .co  m*/
 *
 * @param fs the {@link ProjectFilesystem} that we use to calculate the strong fingerprint.
 * @param includes the list of included build files for which we calculate the strong fingerprint.
 * @param fileHashCache the {@link FileHashCache} object to use to get the content hash of the
 *     loaded files.
 * @return a strong fingerprint - {@link HashCode} that represent a unique hash value.
 * @throws IOException can throw if there is a problem getting the content of the main BUCK build
 *     spec or an included file.
 */
public static HashCode getStrongFingerprint(ProjectFilesystem fs, ImmutableSortedSet<String> includes,
        FileHashCache fileHashCache) throws IOException {
    Hasher hasher = Hashing.sha256().newHasher();

    for (String value : includes) {
        Path value_path = fs.getPath(value);
        hasher.putString(fs.relativize(value_path).toString(), StandardCharsets.UTF_8);
        hasher.putBytes(fileHashCache.get(value_path).asBytes());
    }

    return hasher.hash();
}

From source file:it.anyplace.sync.core.cache.FileBlockCache.java

private @Nullable byte[] pullFile(String code, boolean shouldCheck) {

    final File file = new File(dir, code);
    if (file.exists()) {
        try {/*from   w  ww  .  ja  v a  2 s. c  om*/
            byte[] data = FileUtils.readFileToByteArray(file);
            if (shouldCheck) {
                String cachedDataCode = BaseEncoding.base16()
                        .encode(Hashing.sha256().hashBytes(data).asBytes());
                checkArgument(equal(code, cachedDataCode), "cached data code %s does not match code %s",
                        cachedDataCode, code);
            }
            writerThread.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        FileUtils.touch(file);
                    } catch (IOException ex) {
                        logger.warn("unable to 'touch' file {}", file);
                        logger.warn("unable to 'touch' file", ex);
                    }
                }

            });
            logger.debug("read block {} from cache file {}", code, file);
            return data;
        } catch (Exception ex) {
            logger.warn("error reading block from cache", ex);
            FileUtils.deleteQuietly(file);
        }
    }
    return null;
}

From source file:com.infinities.keystone4j.credential.controller.action.CreateCredentialAction.java

private Credential assignUniqueId(Credential ref, String trustId)
        throws JsonGenerationException, JsonMappingException, IOException {
    if ("ec2".equals(ref.getType().toLowerCase())) {
        Blob blob = null;//from w  w  w .  j  a va2s .co m
        try {
            blob = JsonUtils.readJson(ref.getBlob(), new TypeReference<Blob>() {
            });
        } catch (Exception e) {
            throw Exceptions.ValidationException.getInstance("Invalid blob in credential");
        }

        if (blob == null) {
            throw Exceptions.ValidationException.getInstance(null, "blob", "credential");
        }

        if (Strings.isNullOrEmpty(blob.getAccess())) {
            throw Exceptions.ValidationException.getInstance(null, "access", "blob");
        }

        // logger.debug("blob id before hashing: {}", blob.getId());
        ref.setId(Cms.toHex(Hashing.sha256().hashString(blob.getAccess()).asBytes()));
        // logger.debug("blob id after hashing: {}", blob.getId());
        if (!Strings.isNullOrEmpty(trustId)) {
            blob.setTrustId(trustId);
            ref.setBlob(JsonUtils.toJsonWithoutPrettyPrint(blob));
        }
        return ref;
    } else {
        return assignUniqueId(ref, null);
    }
}