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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With