javax.crypto.spec.SecretKeySpec是线程安全的吗?

huangapple go评论63阅读模式
英文:

Is javax.crypto.spec.SecretKeySpec thread safe?

问题

我打算将其用作 Spring Bean 中的静态字段,并在 post construct 方法中进行初始化。
一个服务类将会注入这个加密 Bean,并调用其暴露的方法,使用 javax.crypto.Cipher 来加密一个字符串(cipher 将使用 SecretKeySpec 进行初始化)。

注意:每次在加密字符串方法内部都会获取一个新的 cipher 实例。

编辑:
正如 @Savior 所指出的,字段(SecretKeySpec)不应被标记为静态。如果 SecretKeySpec 是线程安全的,我将在配置类中将其作为 Bean,并将其注入到加密 Bean 中(将其标记为私有 final 字段,并通过构造函数进行注入)。

英文:

I intend to use it in a spring bean as a static field, and init it inside a post construct method.
A service class will inject this encryption bean and call a method exposed by it to encrypt a string using a cipher (javax.crypto.Cipher) (cipher will be initalized using the SecretKeySpec ).

Note: A new cipher instance will be fetched each time within the encrypt string method.

Edit:
As @Savior noted, the field (SecretKeySpec) should not be denoted as static. If SecretKeySpec is thread safe then I will make it a bean in a configuration class and inject it into the encryption bean (marking it as a private final field and injecting it via constructor)

答案1

得分: 10

是的,没错。很容易看出原因:没有方法(除了下面提到的一个)会改变 SecretKeySpec 实例的状态。换句话说,该类通常是不可变的,即使在类说明中没有明确提到。不可变类从定义上来说是线程安全的。实际上,大多数(如果不是全部)Key 的实现通常都是不可变的。

有一个方法会破坏不可变性(我忘记了),那就是较新的 Key.destroy() 方法。不过不用担心,据我所知,Cipher 或任何其他函数都不会调用它。此外,SecretKeySpec 并未实现这个方法(至少在 OpenJDK 版本 14 中是如此)。


正如评论中也指出的,永远不要将任何动态信息放入静态字段中。相反,只需共享一个引用即可。

英文:

Yes, it is. It's pretty easy to see why: there are no methods (bar one, see below) that change the state of a SecretKeySpec instance. In other words, the class is usually immutable, even if this is not specifically mentioned in the class description. Immutable classes are by definition thread safe. Actually, most if not all Key implementations are generally immutable.

There is one method that breaks the immutability (which I forgot about), and that's the newer Key.destroy() method. Don't worry though, that's not called by Cipher or any other function to my knowledge. Furthermore, the method is not implemented by SecretKeySpec (checked in the OpenJDK up to version 14).


As also noted in the comments, you should never put any dynamic information into static fields. Instead just share a reference otherwise.

huangapple
  • 本文由 发表于 2020年5月29日 23:25:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/62089404.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定