在使用它之前我需要调用 MessageDigest.reset() 吗?
问题很简单:我什么时候应该调用java类MessageDigest上的reset()函数?
这个问题主要来自 OWASP 参考,在代码示例中,他们这样做:
MessageDigest digest = MessageDigest.getInstance("SHA-1");
digest.reset();
digest.update(salt);
byte[] input = digest.digest(password.getBytes("UTF-8"));
然后,在一个循环中,他们这样做:
for (int i = 0; i < iterationNb; i++) {
digest.reset();
input = digest.digest(input);
}
现在,对我来说,看起来好像只有当摘要实例已经被更新调用“污染”时才需要重置。因此,第一个样本中的那个似乎没有必要。如果有必要,是否表明MessageDigest.getInstance返回的实例不是线程安全的?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为你是对的,最初的
reset()
是没有必要的。 文档指出:此外,类文档中的示例不包括初始重置。
这与线程安全无关,
.reset()
的必要性只是表明getInstance()
本身不进行初始化。无论如何,您不应该在没有同步的情况下从多个线程使用相同的 MessageDigest 对象:只有当您知道各部分的散列顺序时,散列才有意义,否则它只是一个奇特的非完全确定性 PRNG。
I think you are right, the initial
reset()
is not necessary. The documentation states: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 thatgetInstance()
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.