What does MessageDigest.update(byte[]) do?
Asked Answered
T

1

13

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.

Timid answered 22/7, 2013 at 11:41 Comment(4)
Your code looks fine. Its the right way to create a salted digest of a value.Paraffinic
Did you look at the API documentation?Larainelarboard
@Paraffinic Thank you for confirming :)Timid
@Larainelarboard Unfortunately that documentation and all of the other ones that I found, don't explain much.Timid
D
17

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]
Dinner answered 22/7, 2013 at 11:50 Comment(2)
Appreciate the elaborated explanation, follow up question: so all what update does is concatenate the arrays together, nothing else special?Timid
When we give a MessageDigest an array it simply iterates over this array and updates digest by byteDinner

© 2022 - 2024 — McMap. All rights reserved.