Is the cipher thread safe?

Simply put, can a single javax.crypto.Cipher instance (for example, Cipher.getInstance("RSA") ) be used from multiple threads, or do I need to insert several of them into ThreadLocal (in my case)?

+44
java multithreading thread-safety encryption
Aug 05 '11 at 13:52
source share
3 answers

No, it is not. Instance is a state. Therefore, you need to save its threadlocal or get a new instance every time you call encryption / decryption or wrap it in a synchronized(cipher) block.

Threadsafety is usually explicitly mentioned in javadocs. This does not apply to Cipher , so you should not consider it thread safe.

+72
Aug 05 2018-11-11T00:
source share

Even if Cipher was thread safe, it would be useless to use it from multiple threads at the same time.

The bytes that you insert and exit Cipher (through the update and finish methods) are a continuous stream. This means that, on the other hand, they must be transmitted in the same order in order to make any sense. This is easiest to do if you have only one thread.

If you use multiple threads, you usually want to call reset between calls - and then you need external synchronization.

+5
Aug 05 2018-11-11T00:
source share

I would not use Cipher objects from multiple threads without synchronization. When you look at the API, there are methods that can only work when the internal state changes, such as init() and update() . This makes them implicitly unsafe.

+4
Aug 05 2018-11-11T00:
source share



All Articles