Is SecureRandom.ints() secure?

Random.ints() is a method that returns an IntStream. An IntStream is neither secure nor insecure: it's a stream of numbers.

The "security" of the sequence of ints returned by the method depends on the implementation of the method. SecureRandom generates its "random" values more securely than Random. They share the same API, and thus you can use either in a given context depending upon your requirements.

So, the fact it inherits from an insecure class is irrelevant to the security: you can reasonably trust that the SecureRandom class is as secure as the documentation says it is.


Consider an analogy with HashSet: this makes no guarantees of the iterator ordering; however, LinkedHashSet, a subclass of HashSet does guarantee iterator ordering. The guarantee of LinkedHashSet is consistent with the guarantee of HashSet, because a specific ordering is one of the possible orderings that could be observed with "no guaranteed ordering" (after all, you have to return the elements in some order).

Similarly, Random makes no guarantees about the security of the sequence of ints returned; SecureRandom makes stronger guarantees. But there is no reason why the sequence of ints from a SecureRandom couldn't also be returned by a Random, by coincidence.


Yes it is secure.

Code examination of java.util.Random shows that ints() creates a spliterator that uses internalNextInt(...) to generate the random integers. That in turn calls nextInt() on this. In the case of java.security.SecureRandom, nextInt() is overridden to generate a "secure" random number1.

You can confirm this for yourself by looking at the source code.


1 - Of course, it doesn't actually make sense to call an integer or a sequence of integers "secure". And there are situations where SecureRandom may not have the properties that you require. (It depends on the actual RNG or PRNG implementation used by the class, the quality of the supplied seed or system provided entropy source, and so on.) But SecureRandom::ints() will generate a sequence of integers that has the same properties as if you made a sequence of SecureRandom::nextInt() calls on the same object. If the latter sequence is suitable for your purposes (whatever they are) then so is the former.