François Lamarre François Lamarre - 1 year ago 106
Java Question

Do I need to call MessageDigest.reset() before using it?

The question is simple: when should I call the reset() function on the java class MessageDigest?

The question mainly comes from the OWASP reference, where in a code sample, they do:

MessageDigest digest = MessageDigest.getInstance("SHA-1");
byte[] input = digest.digest(password.getBytes("UTF-8"));

then, in a loop, they do:

for (int i = 0; i < iterationNb; i++) {
input = digest.digest(input);

Now, to me, it looks as if the reset is only required once the digest instance has already been 'polluted' with calls to update. The one in the first sample, therefore, does not seem necessary. If it is necessary, is it an indication that the instance returned by MessageDigest.getInstance is not thread safe?

Answer Source

I think you are right, the initial reset() is not necessary. The documentation states:

A MessageDigest object starts out initialized.

Also the example on the class documentation does not include the initial reset.

This has nothing to do with thread-safety, the necessity of .reset() would just indicate that getInstance() does not do the initialization itself.

You should not use the same MessageDigest object from multiple threads without synchronization anyway: A hash is only meaningful if you know in which order the parts were hashed, otherwise it is just a fancy not-totally-deterministic PRNG.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download