And another question. Trying out to debug my quest...
# announcements
i
And another question. Trying out to debug my question above in a scratch file, I got the same output for 2 different digest instances, with different data. What am I missing?
Copy code
val digest = MessageDigest.getInstance("SHA-256")
digest.update("bar".toByteArray())
val str = digest.digest().toString(UTF_8)

val digest2 = MessageDigest.getInstance("SHA-256")
digest2.update("sldkjfskfjs".toByteArray())
val str2 = digest2.digest().toString(UTF_8)

// str == str2 --> true!
j
Don't use toString() for comparison. It's not the actual API just used for debugging. More importantly, digest and digest2 refer to the same singleton instance. You'll need to do a reset()
i
ah that makes sense. What to use here instead of
toString()
?
ah, I guess the
String
factory method:
String.create(bytes, encoding)
it's very weird though, even if the digest instance is the same, I'm "capturing" the output of the first part in
str
, modifying this instance and then "capturing" the second part.
don't see why they would be the same? And both using
String.create
and calling
reset
on
digest
don't help, apparently. It's still
true
j
Have you thought about using something like okio instead of the Java MessageDigest?
try
val digestArray = digest.digest("bar".toByteArray())
i
I wanted to test specifically the behavior or
update
. This code is from a third party library.
(so I can't use something else. Just wanted to verify)
j
I think the real problem is converting the byte[] returned from digest() into a String. It's not meant for that - may contain embedded nulls, etc... Try
Arrays.equals(arr1, arr2)
a
I don’t get str to equal str2 when I try out your example code (I didn’t do anything but put it into a junit method)
MessageDigest.getInstance
returns a new instance of a digester, not a singleton. Afaik,
update
should effectively append, i.e. it consumes more data and updates the digest.
You can write
arr1 contentEquals arr2
in Kotlin
j
Technically, your "foo" and "bar" updates should have the same digest as "foobar". MessageDigest also has a static isEqual() method that can compare the byte arrays. The problem is actually a lot deeper.. I'm getting different results when I execute in a scratchpad and when I actually run it inside a compiled class. In the scratchpad, the update calls just seem to be ignored.
My experimentation suggests digest() does an implicit reset(), while update() lets you append to the buffer before calling digest().. However, for some reason this does not work in a scratchpad environment 😕
i
hmm. Weird. Luckily this is not something I've to figure out (just wanted to confirm quickly what update does).
thanks either way for the answers everyone