Is Cipher thread-safe?
Quite simply, can one instance of javax.crypto.Cipher
(e.g. Cipher.getInstance("RSA")
) be used from multiple threads, or do I need to stick multiple of them in a ThreadLocal
(in my case)?
No, it isn't. The instance is stateful. So you need to store it threadlocal, or to obtain a new instance on every encrypt/decrypt call, or to wrap it in a synchronized(cipher)
block.
Threadsafety is usually explicitly mentioned in javadocs. This is not the case for Cipher
, so you should not assume it to be threadsafe.
I wouldn't use Cipher objects from multiple threads without synchronization. When you look at the API, there are methods which can only work by changing internal state, such as init()
and update()
. That makes them implicitly non-thread-safe.
Even if a Cipher was thread-safe, it would not really be useful to use it from multiple threads concurrently.
The bytes you put into and get out of the Cipher (via its update
and finish
methods) are a continuous stream. This means, on the other end, they have to be passed in the same order to make any sense. This is easiest to accomplish if you have only one thread doing this.
If you are using multiple threads, you usually would want to call reset
between the calls - and then you will need external synchronization anyways.
Cipher is not thread safe.
If you use multithreading for performance and don't want to do synchronization, you can use Jasypt (http://www.jasypt.org/general-usage.html) it has pooled encryptors: PooledPBEByteEncryptor, PooledPBEStringEncryptor.
If synchronization is ok for you and you use Spring. You can use Encryptors (https://docs.spring.io/spring-security/site/docs/4.2.5.RELEASE/apidocs/org/springframework/security/crypto/encrypt/Encryptors.html). They do synchronization internally to access Cipher.
ReferenceURL : https://stackoverflow.com/questions/6957406/is-cipher-thread-safe
'Programing' 카테고리의 다른 글
What is the basic concept behind WaitHandle? (0) | 2020.12.24 |
---|---|
PHP - print all properties of an object (0) | 2020.12.24 |
새 행에서 선택 가능한 영역을 작게 만들지 않고 WPF DataGrid 셀을 오른쪽 정렬하는 방법은 무엇입니까? (0) | 2020.12.24 |
MongoDB의 기본 데이터베이스 경로는 무엇입니까? (0) | 2020.12.24 |
_.debounce는 무엇을합니까? (0) | 2020.12.24 |