开发者

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开发者_Go百科 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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜