在使用它之前我需要调用 MessageDigest.reset() 吗?

发布于 2024-12-06 09:56:48 字数 852 浏览 5 评论 0原文

问题很简单:我什么时候应该调用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

安静被遗忘 2024-12-13 09:56:48

我认为你是对的,最初的 reset() 是没有必要的。 文档指出

MessageDigest 对象开始时已初始化。

此外,类文档中的示例不包括初始重置。

这与线程安全无关,.reset() 的必要性只是表明 getInstance() 本身不进行初始化。

无论如何,您不应该在没有同步的情况下从多个线程使用相同的 MessageDigest 对象:只有当您知道各部分的散列顺序时,散列才有意义,否则它只是一个奇特的非完全确定性 PRNG。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文