Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is KeyPairGenerator.generateKeyPair() thread safe?

Asking as the KeyPairGenerator.initialize() method takes a SecureRandom instance which is expensive to initialize. Java Doc does not mention anything about it being thread-safe. All I can find is a comment in the source code. Could it be that it depends on the actual KeyPairGenerator instance created? By the way, I am using the Sun RSA instance.

like image 894
neurite Avatar asked Sep 05 '14 17:09

neurite


People also ask

Is KeyGenerator thread safe?

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..

What is KeyPairGenerator?

The KeyPairGenerator class is used to generate pairs of public and private keys. Key pair generators are constructed using the getInstance factory methods (static methods that return instances of a given class).


1 Answers

It does depend on the actual instance created, neurite, as you surmised. It is important to note that the KeyPairGenerator class is abstract, and implementing subclasses override the generateKeyPair method. Thus, the authors of the abstract class KeyPairGenerator are not in a position to claim that it is thread-safe. All they could do is ensure that they did nothing to compromise thread safety.

The standard way of getting a KeyPairGenerator using the static getInstance method returns an instance of a class derived from KeyPairGenerator: see the KeyPairGenerator.Delegate class. Its implementation of generateKeyPair also does nothing to compromise thread safety, so if you get your KeyPairGenerator that way, you are fine. But you could also get a KeyPairGenerator like this:

    KeyPairGenerator kpg=new KeyPairGenerator("RSA"){
        @Override
        public KeyPair generateKeyPair(){
            return doSomethingThatIsntThreadSafe();
        }
    };

Now of course, you would never do this, but the authors of KeyPairGenerator can't know that, so they can't tell you that any instance of KeyPairGenerator is thread-safe.

† where fine means dependent on your cryptography SPI to do the right thing!

like image 57
Breandán Dalton Avatar answered Oct 19 '22 22:10

Breandán Dalton