11

What exactly does this do? I tried to look it up but didn't find anything.

Reason for asking is I want to incorporate a SALT byte[] into a value which is then hashed. So should it be done like this (Pseudo code):

MessageDigest.update(SALT);
MessageDigest.update(value);
digestValue = MessageDigest.digest();
// Where SALT, value and digestValue are array bytes, byte[]

Does this add both SALT and value to the final digest or should I combine both variables into one and then update it once?

I couldn't find an answer for this in any documentation, any clarification would be appreciated.

Thank you, cheers.

LuckyMe
  • 3,820
  • 2
  • 27
  • 35

1 Answers1

15

MessageDigest is statefull, calls of MessageDigest.update(byte[] input) accumulate digest updates until we call MessageDigest.digest. Run this test to make sure:

    MessageDigest md1 = MessageDigest.getInstance("MD5");
    md1.update(new byte[] {1, 2});
    md1.update(new byte[] {3, 4});
    System.out.println(Arrays.toString(md1.digest()));

    MessageDigest md2 = MessageDigest.getInstance("MD5");
    md2.update(new byte[] {1, 2, 3, 4});
    System.out.println(Arrays.toString(md2.digest()));

output

[8, -42, -64, 90, 33, 81, 42, 121, -95, -33, -21, -99, 42, -113, 38, 47]
[8, -42, -64, 90, 33, 81, 42, 121, -95, -33, -21, -99, 42, -113, 38, 47]
Kevin Kopf
  • 13,327
  • 14
  • 49
  • 66
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • Appreciate the elaborated explanation, follow up question: so all what `update` does is concatenate the arrays together, nothing else special? – LuckyMe Jul 22 '13 at 19:23
  • When we give a MessageDigest an array it simply iterates over this array and updates digest by byte – Evgeniy Dorofeev Jul 23 '13 at 03:37