views:

37

answers:

2

Coming from the C++ world here, thus the nature of the question...

I want to use a single SecureRandom generator in a Java application, but I need several instances of a class to store a reference to it in the constructor, rather than copies.

So,

public class MyClass {
    private SecureRandom random;
    public MyClass(SecureRandom _random) { random = _random };
... }

Does this result in a reference to the same generator, or a copy of it? The problem with a copy is that constructing several MyClass objects one after the other will result in identical sequences if the SecureRandom is a pseudorandom one such as SHA1PRNG. What I need is them to share a single one so that sequences of calls to random.nextBytes(...) will give me different results within each MyClass instance.

(By the way, is SHA1PRNG guaranteed to be seeded a different way each time a new instance of SecureRandom is created in the main application, and hopefully in a more secure way than the time?)

+1  A: 

The same one. random and _random are reference variables pointing to the same object.

Matthew Flaschen
+3  A: 

In Java anything that is not a primitive type (boolean, char, byte, short, int, long, float, double) is a reference type. The only way to copy a reference type is to do so explicitly through cloning, serialization, copy-constructing, etc. You're not using clone() or its ilk there, and you're not using a constructor. You're just doing assignment. This means you're copying the reference.

JUST MY correct OPINION