Don't understand Guava PrimitiveSink

I thought about learning some new things and started using Google Guava in a new small project.

One of the first things I had to do was implement simple key exchange authentication.

The plan was to combine some values ​​and generate a SHA256 hash.

In pure Java, this is

    final String toHash = id + ts + secret;
    final MessageDigest digest = MessageDigest.getInstance("SHA-256");
    final byte[] hash = digest.digest(toHash.getBytes("UTF-8"));
    final String result = getHexFormated(hash)

In Guava I tried

    final Hasher hasher = Hashing.sha256().newHasher().putString(id, Charsets.UTF_8)
        .putLong(ts).putString(secret, Charsets.UTF_8);
    final HashCode hashcode = hasher.hash();

If I compare the first result with hashcode.toString (), it is completely different. If I compare the byte [] itself to make sure that not getHexFormated is wrong, the byte arrays are also completely different.

So what's the problem? What does PrimitiveSink do instead of simply combining these values?

+3
source share
1 answer

In your first snippet you will do:

final String toHash = id + ts + secret;

ts - long; .

:

.putLong(ts)

, ...

.putString(String.valueOf(ts))

.

+4

All Articles