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:endpoint.AccountEndpoint.java

public void checkAndChangePassword(String oldPassword, String newPassword) throws AppBaseException {
    Account myAccount = findMyAccount();
    String sha256PasswordOld = Hashing.sha256().hashString(oldPassword, Charsets.UTF_8).toString();
    if (!sha256PasswordOld.equals(myAccount.getPassword()))
        throw new IllegalArgumentException("Podane haso jest nieprawidowe");
    String sha256PasswordNew = Hashing.sha256().hashString(newPassword, Charsets.UTF_8).toString();
    changePassword(myAccount, sha256PasswordNew);
}

From source file:com.cinchapi.common.io.Files.java

/**
 * A version of the {@link #directoryChecksum(String)} method that uses
 * metadata caching for the {@code directory} to speed up checksum
 * calculations, where possible./*  w  w w. j av  a2 s.  co  m*/
 * <p>
 * Do not use this method for security operations because there are subtle
 * race conditions and possible exploits that can happen when using metadata
 * caching. However, this method is appropriate to use for validating the
 * integrity of files in non-critical situations or those where the
 * likelihood of tampering is low.
 * </p>
 * 
 * @param directory the directory whose checksum is generated
 * @return the checksum of the directory
 */
public static String directoryChecksumCached(String directory) {
    Path cache = Paths.get(USER_HOME).resolve(Paths.get(".cinchapi", "accent4j", ".checksums",
            Hashing.sha256().hashString(directory, StandardCharsets.UTF_8).toString()));
    File file = cache.toFile();
    try {
        String checksum;
        long directoryLastModified = getMostRecentFileModifiedTime(directory).toMillis();
        if (file.exists()
                && getMostRecentFileModifiedTime(cache.toString()).toMillis() > directoryLastModified) {
            checksum = Iterables.getOnlyElement(readLines(cache.toString()));
        } else {
            checksum = directoryChecksum(directory);
            Thread.sleep(1000); // avoid race condition with file
                                // modification timestamps because many file
                                // systems only have granularity within 1
                                // second.
            file.getParentFile().mkdirs();
            file.createNewFile();
            com.google.common.io.Files.asCharSink(file, StandardCharsets.UTF_8).write(checksum);
        }
        return checksum;

    } catch (IOException | InterruptedException e) {
        throw CheckedExceptions.throwAsRuntimeException(e);
    }
}

From source file:uk.ac.horizon.artcodes.server.christmas.ImageServlet.java

@Override
public void doPut(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {/* ww w  . j  a  v a  2  s . c  om*/
        if (request.getContentLength() > image_size) {
            throw new HTTPException(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, "Image too large");
        }

        verifyApp(request);
        final String id = getImageID(request);
        final GcsService gcsService = GcsServiceFactory.createGcsService(RetryParams.getDefaultInstance());
        final GcsFilename filename = new GcsFilename(request.getServerName(), id);

        final GcsFileMetadata metadata = gcsService.getMetadata(filename);
        if (metadata != null) {
            throw new HTTPException(HttpServletResponse.SC_FORBIDDEN, "Cannot modify");
        }

        final BufferedInputStream inputStream = new BufferedInputStream(request.getInputStream());
        final String mimetype = URLConnection.guessContentTypeFromStream(inputStream);
        if (mimetype == null) {
            throw new HTTPException(HttpServletResponse.SC_BAD_REQUEST, "Unrecognised image type");
        }

        final GcsFileOptions.Builder fileOptionsBuilder = new GcsFileOptions.Builder();
        fileOptionsBuilder.mimeType(mimetype);
        final GcsFileOptions fileOptions = fileOptionsBuilder.build();
        final GcsOutputChannel outputChannel = gcsService.createOrReplace(filename, fileOptions);

        final HashingOutputStream outputStream = new HashingOutputStream(Hashing.sha256(),
                Channels.newOutputStream(outputChannel));
        ByteStreams.copy(inputStream, outputStream);

        String hash = outputStream.hash().toString();
        if (!hash.equals(id)) {
            gcsService.delete(filename);
            throw new HTTPException(HttpServletResponse.SC_BAD_REQUEST, "Invalid hash");
        }

        outputStream.close();
        outputChannel.close();
    } catch (HTTPException e) {
        e.writeTo(response);
    }
}

From source file:it.anyplace.sync.core.security.KeystoreHandler.java

public static String derDataToDeviceIdString(byte[] certificateDerData) {
    return hashDataToDeviceIdString(Hashing.sha256().hashBytes(certificateDerData).asBytes());
}

From source file:it.anyplace.sync.core.security.KeystoreHandler.java

public static String hashDataToDeviceIdString(byte[] hashData) {
    checkArgument(hashData.length == Hashing.sha256().bits() / 8);
    String string = BaseEncoding.base32().encode(hashData).replaceAll("=+$", "");
    string = Joiner.on("")
            .join(Iterables.transform(Splitter.fixedLength(13).split(string), new Function<String, String>() {
                @Override/*from ww  w  .j a  va  2s .  c o  m*/
                public String apply(String part) {
                    return part + generateLuhn32Checksum(part);
                }
            }));
    return Joiner.on("-").join(Splitter.fixedLength(7).split(string));
}

From source file:com.github.nethad.clustermeister.api.Credentials.java

/**
 * Get a {@link Supplier} that returns the hex-string representation of the 
 * input's SHA-256 hash.//from w ww  .ja v a2  s .c om
 * 
 * The hash is only computed once and cached for further requests.
 * 
 * @param string the input.
 * @param charset   the charset of the input.
 * @return the hexadecimal string  representation of the {@code input}s hash code.
 */
protected Supplier<String> getSha256DigestSupplier(final String string, final Charset charset) {

    return Suppliers.memoize(new Supplier<String>() {

        @Override
        public String get() {
            if (string == null || string.isEmpty()) {
                return string;
            }
            HashFunction hf = Hashing.sha256();
            HashCode hc = hf.newHasher(string.length()).putString(string, charset).hash();
            return hc.toString();
        }
    });
}

From source file:io.prestosql.plugin.ml.ModelUtils.java

public static Model deserialize(Slice slice) {
    int version = slice.getInt(VERSION_OFFSET);
    checkArgument(version == CURRENT_FORMAT_VERSION, format("Unsupported version: %d", version));

    byte[] modelHashBytes = slice.getBytes(HASH_OFFSET, 32);
    HashCode expectedHash = HashCode.fromBytes(modelHashBytes);
    HashCode actualHash = Hashing.sha256()
            .hashBytes(slice.getBytes(ALGORITHM_OFFSET, slice.length() - ALGORITHM_OFFSET));
    checkArgument(actualHash.equals(expectedHash), "model hash does not match data");

    int id = slice.getInt(ALGORITHM_OFFSET);
    Class<? extends Model> algorithm = MODEL_SERIALIZATION_IDS.inverse().get(id);
    requireNonNull(algorithm, format("Unsupported algorith %d", id));

    int hyperparameterLength = slice.getInt(HYPERPARAMETER_LENGTH_OFFSET);

    byte[] hyperparameterBytes = slice.getBytes(HYPERPARAMETERS_OFFSET, hyperparameterLength);

    int dataLengthOffset = HYPERPARAMETERS_OFFSET + hyperparameterLength;
    long dataLength = slice.getLong(dataLengthOffset);

    int dataOffset = dataLengthOffset + SIZE_OF_LONG;
    byte[] data = slice.getBytes(dataOffset, (int) dataLength);

    try {// ww  w  .  jav a  2s .  c  om
        Method deserialize = algorithm.getMethod("deserialize", byte[].class);
        return (Model) deserialize.invoke(null, new Object[] { data });
    } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}

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

public static Model deserialize(Slice slice) {
    int version = slice.getInt(VERSION_OFFSET);
    checkArgument(version == CURRENT_FORMAT_VERSION, format("Unsupported version: %d", version));

    byte[] modelHashBytes = slice.getBytes(HASH_OFFSET, 32);
    HashCode expectedHash = HashCode.fromBytes(modelHashBytes);
    HashCode actualHash = Hashing.sha256()
            .hashBytes(slice.getBytes(ALGORITHM_OFFSET, slice.length() - ALGORITHM_OFFSET));
    checkArgument(actualHash.equals(expectedHash), "model hash does not match data");

    int id = slice.getInt(ALGORITHM_OFFSET);
    Class<? extends Model> algorithm = MODEL_SERIALIZATION_IDS.inverse().get(id);
    requireNonNull(algorithm, format("Unsupported algorith %d", id));

    int hyperparameterLength = slice.getInt(HYPERPARAMETER_LENGTH_OFFSET);

    byte[] hyperparameterBytes = slice.getBytes(HYPERPARAMETERS_OFFSET, hyperparameterLength);

    int dataLengthOffset = HYPERPARAMETERS_OFFSET + hyperparameterLength;
    long dataLength = slice.getLong(dataLengthOffset);

    int dataOffset = dataLengthOffset + SIZE_OF_LONG;
    byte[] data = slice.getBytes(dataOffset, (int) dataLength);

    try {//from  ww w  .  j a v a2s .c o  m
        Method deserialize = algorithm.getMethod("deserialize", byte[].class);
        return (Model) deserialize.invoke(null, new Object[] { data });
    } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
        throw Throwables.propagate(e);
    }
}

From source file:org.opennms.features.topology.app.internal.support.LayoutManager.java

protected static String calculateHash(Collection<VertexRef> vertices) {
    final String vertexKey = vertices.stream()
            .sorted(Comparator.comparing(VertexRef::getNamespace).thenComparing(VertexRef::getId))
            .map(v -> String.format("%s:%s", v.getNamespace(), v.getId())).collect(Collectors.joining(","));
    return Hashing.sha256().hashString(vertexKey, Charsets.UTF_8).toString();
}

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

@Override
public AsyncLeaderElector newAsyncLeaderElector(String name) {
    checkNotNull(name);/*from w ww  . ja  v  a 2 s  . com*/
    Map<PartitionId, AsyncLeaderElector> leaderElectors = Maps.transformValues(members,
            partition -> partition.newAsyncLeaderElector(name));
    Hasher<String> hasher = topic -> {
        int hashCode = Hashing.sha256().hashString(topic, Charsets.UTF_8).asInt();
        return sortedMemberPartitionIds.get(Math.abs(hashCode) % members.size());
    };
    return new PartitionedAsyncLeaderElector(name, leaderElectors, hasher);
}