Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is KeyGenerator thread safe?

I am wondering if I can instantiate the javax.crypto.KeyGenerator only once and then use this instance in a multithread environment.

Its JavaDoc documentation does not say anything about its thread-safeness. Or it will be better to use a ThreadLocal<KeyGenerator> approach?

UPDATE: A related question is Is SecureRandom thread safe? While the JavaDoc doesn't state that class is thread safe, the community still found the decision that it is thread-safe what is quite important from the practical point of view. I would like to know the same for the KeyProvider.

like image 677
Andremoniy Avatar asked Dec 06 '17 16:12

Andremoniy


1 Answers

Unless the documentation explicitly guarantees thread-safety then treat anything as if it is not thread-safe.

You're right this philosophy is hardly helpful with the scarcity of thread-safety documentation... But without the documentation guaranteeing thread-safety then you simply can't assume something is or will continue to be thread-safe.


Here's some research into the actual implementation of KeyGenerator and why we can't assume that it's thread safe

I found the source and at first glance it would seem like the current implementation is thread safe. However, even if we were to assume this implementation were to never change, it makes calls to Security Providers which could be any implementation of their own and also have no guarantee of being thread-safe since the documentation says nothing about it.


Summary of the source:

Calls to generateKey() use a "Key Generator Service Provider" calling KeyGeneratorSpi.engineGenerateKey() (which could be thread-unsafe) to generate the SecretKey.

If you constructed the KeyGenerator with a specific provider then it will use that specific provider to generate the key.

If you did not construct KeyGenerator with a specific provider then nextSpi() will iterate (thread-safely) through the JVMs list of available providers and try to generate the key until one works or you run out of providers..


The main point is documentation... If the documentation says nothing about thread-safety then any current implementer or an update to the current implementation might not be thread safe.

So you simply cannot assume or depend on any thread safety from KeyGenerator.

like image 152
xtratic - Reinstate Monica Avatar answered Oct 21 '22 12:10

xtratic - Reinstate Monica