Search code examples
javadigestmessage-digest

Message Digest java


I was not aware of the MessageDigest class before. I am now trying to understand a segment of code and the documentation is not helping me much.

MessageDigest digest = Crypto.sha256();

digest.update(last.getSign());
byte[] SignHash = digest.digest(publicKey);

According to the java documentation:

"update" Updates this MessageDigest using the given byte[]

"digest" Performs the final update and then computes and returns the final hash value for this MessageDigest.

Question 1: What does "updates using the given byte[]" really mean?

Question 2: What is the final update performed by "digest" ?

Does the above mean SignHash=sha256(last.getSign() concat (some padding of public key)) ?


Solution

  • Think of the MessageDigest class as if updating it is really appending more bytes to an internal buffer. Now once you're done, you use the digest method to create a hash of all the bytes appended to the buffer.

    The naming might seem a bit strange (I certainly think that "appendBytes" and "createHash"/"createDigest" would have been better), but think about the MessageDigest instance, which internal state you update with more bytes, until you finally generate the digest.