Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is javax.crypto.spec.SecretKeySpec thread safe?

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)

like image 506
bobbyBo182 Avatar asked Mar 02 '23 10:03

bobbyBo182


1 Answers

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.

like image 165
Maarten Bodewes Avatar answered Mar 05 '23 18:03

Maarten Bodewes