Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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");
   digest.reset();
   digest.update(salt);
   byte[] input = digest.digest(password.getBytes("UTF-8"));

then, in a loop, they do:

   for (int i = 0; i < iterationNb; i++) {
       digest.reset();
       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?

  • OWASP hashing recommendation
  • Random article on hashing, does not contain initial reset
like image 864
François Lamarre Avatar asked Oct 10 '22 22:10

François Lamarre


1 Answers

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.

like image 145
Paŭlo Ebermann Avatar answered Oct 13 '22 09:10

Paŭlo Ebermann