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:org.apache.servicecomb.demo.edge.service.encrypt.filter.EdgeSignatureRequestFilter.java

@Override
public Response afterReceiveRequest(Invocation invocation, HttpServletRequestEx requestEx) {
    EncryptContext encryptContext = (EncryptContext) invocation.getHandlerContext()
            .get(EdgeConst.ENCRYPT_CONTEXT);
    if (encryptContext == null) {
        return null;
    }/*from w  ww.  j  a  va2 s  .co  m*/
    Hcr hcr = encryptContext.getHcr();

    // signature for query and form
    List<String> names = Collections.list(requestEx.getParameterNames());
    names.sort(Comparator.naturalOrder());

    Hasher hasher = Hashing.sha256().newHasher();
    hasher.putString(hcr.getSignatureKey(), StandardCharsets.UTF_8);
    for (String name : names) {
        hasher.putString(name, StandardCharsets.UTF_8);
        hasher.putString(requestEx.getParameter(name), StandardCharsets.UTF_8);
    }
    LOGGER.info("afterReceiveRequest signature: {}", hasher.hash().toString());

    return null;
}

From source file:lbaas.util.HashAlgorithm.java

public int hash(Object key) {
    HashCode hashCode;//from   w  w w  . j  a v a2s . co m
    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 hashCode.asInt();
}

From source file:org.sfs.encryption.CipherWriteStreamValidation.java

public CipherWriteStreamValidation(byte[] secretBytes, byte[] salt) {
    this.salt = salt.clone();
    secretBytes = secretBytes.clone();//w  ww. ja v a  2s. com
    if (secretBytes.length != KEY_SIZE_BYTES) {
        secretBytes = Hashing.sha256().hashBytes(secretBytes).asBytes();
    }
    try {
        KeyParameter key = new KeyParameter(secretBytes);
        AEADParameters params = new AEADParameters(key, MAC_SIZE_BITS, this.salt);

        this.encryptor = new GCMBlockCipher(new AESFastEngine());
        this.encryptor.init(true, params);

        this.decryptor = new GCMBlockCipher(new AESFastEngine());
        this.decryptor.init(false, params);

    } catch (Exception e) {
        throw new RuntimeException("could not create cipher for AES256", e);
    } finally {
        Arrays.fill(secretBytes, (byte) 0);
    }
}

From source file:org.apache.james.backend.rabbitmq.DockerClusterRabbitMQExtension.java

public void beforeAll() {
    String cookie = Hashing.sha256().hashString("secret cookie here", StandardCharsets.UTF_8).toString();

    network = Network.NetworkImpl.builder().enableIpv6(false).createNetworkCmdModifiers(ImmutableList.of())
            .build();// w w w.j  av  a  2s .  c  o m

    String clusterIdentity = UUID.randomUUID().toString();
    rabbitMQ1 = DockerRabbitMQ.withCookieAndHostName(RABBIT_1, clusterIdentity, cookie, network);
    rabbitMQ2 = DockerRabbitMQ.withCookieAndHostName(RABBIT_2, clusterIdentity, cookie, network);
    rabbitMQ3 = DockerRabbitMQ.withCookieAndHostName(RABBIT_3, clusterIdentity, cookie, network);

    startDockerRabbits();
}

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:/*from   ww  w .  j a  v a  2  s .c  o  m*/
        return Hashing.sha1();
    }
}

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

/**
 * Gets the weak fingerprint for this configuration.
 *
 * @param buildFile the path to the BUCK file build spec of interest.
 * @param config the {@link Config} object to calculate the weak fingerprint for
 * @return a weak fingerprint - {@link com.google.common.hash.HashCode} that represent a unique
 *     hash value.//from   w w  w  .  j  a v a 2 s  .  c  om
 */
public static HashCode getWeakFingerprint(Path buildFile, Config config) {
    Hasher hasher = Hashing.sha256().newHasher();
    return hasher.putString(buildFile.toString(), StandardCharsets.UTF_8)
            .putBytes(config.getOrderIndependentHashCode().asBytes())
            .putString(Platform.detect().name(), StandardCharsets.UTF_8)
            .putString(Architecture.detect().name(), StandardCharsets.UTF_8).hash();
}

From source file:org.apache.servicecomb.it.edge.encrypt.filter.EdgeSignatureResponseFilter.java

@Override
public void beforeSendResponse(Invocation invocation, HttpServletResponseEx responseEx) {
    if (invocation == null) {
        return;/*from   w  ww . jav  a  2 s . c  o m*/
    }

    EncryptContext encryptContext = (EncryptContext) invocation.getHandlerContext()
            .get(EdgeConst.ENCRYPT_CONTEXT);
    if (encryptContext == null) {
        return;
    }
    Hcr hcr = encryptContext.getHcr();

    // bad practice: it's better to set signature in response header
    Buffer bodyBuffer = responseEx.getBodyBuffer();
    String body = bodyBuffer.toString();
    if (body.endsWith("}")) {
        Hasher hasher = Hashing.sha256().newHasher();
        hasher.putString(hcr.getSignatureKey(), StandardCharsets.UTF_8);
        hasher.putString(body, StandardCharsets.UTF_8);
        String signature = hasher.hash().toString();
        LOGGER.info("beforeSendResponse signature: {}", signature);

        body = body.substring(0, body.length() - 1) + ",\"signature\":\"" + signature + "\"}";
        responseEx.setBodyBuffer(Buffer.buffer(body));
    }
}

From source file:org.eclipse.kapua.service.datastore.internal.elasticsearch.EsDocumentBuilder.java

private String getHashCode(String aString) {
    byte[] hashCode = Hashing.sha256().hashString(aString, StandardCharsets.UTF_8).asBytes();

    return Base64.encodeBytes(hashCode);
    // return aString;
}

From source file:com.google.devtools.build.lib.bazel.repository.HttpDownloader.java

/**
 * Attempt to download a file from the repository's URL. Returns the path to the file downloaded.
 *//*from   w  w w  . ja  va2  s  . c o  m*/
public Path download() throws IOException {
    String filename = new PathFragment(url.getPath()).getBaseName();
    if (filename.isEmpty()) {
        filename = "temp";
    }
    Path destination = outputDirectory.getRelative(filename);

    try (OutputStream outputStream = destination.getOutputStream()) {
        ReadableByteChannel rbc = getChannel(url);
        ByteBuffer byteBuffer = ByteBuffer.allocate(BUFFER_SIZE);
        while (rbc.read(byteBuffer) > 0) {
            byteBuffer.flip();
            while (byteBuffer.hasRemaining()) {
                outputStream.write(byteBuffer.get());
            }
            byteBuffer.flip();
        }
    } catch (IOException e) {
        throw new IOException("Error downloading " + url + " to " + destination + ": " + e.getMessage());
    }

    String downloadedSha256;
    try {
        downloadedSha256 = getHash(Hashing.sha256().newHasher(), destination);
    } catch (IOException e) {
        throw new IOException("Could not hash file " + destination + ": " + e.getMessage()
                + ", expected SHA-256 of " + sha256 + ")");
    }
    if (!downloadedSha256.equals(sha256)) {
        throw new IOException("Downloaded file at " + destination + " has SHA-256 of " + downloadedSha256
                + ", does not match expected SHA-256 (" + sha256 + ")");
    }
    return destination;
}

From source file:uk.ac.nott.mrl.arch.Item.java

static void updateCurrent() {
    final String json = gson.toJson(current);
    final String tag = Hashing.sha256().hashString(json, charset).toString();
    if (!tag.equals(currentTag)) {
        currentTag = tag;/* www  . ja v  a2s.  c o m*/
        currentJson = json;
        logger.info(currentJson);
    }
}