Is Cipher thread-safe?

Bart van Heukelom picture Bart van Heukelom · Aug 5, 2011 · Viewed 22.2k times · Source

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)?

Answer

BalusC picture BalusC · Aug 5, 2011

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 mentioned in javadocs as "is thread safe" or "is not thread safe". This is not the case for Cipher, so you should not assume it to be threadsafe.