SecureRandom.generateSeed() and unnecessary garbage

Weijun Wang at
Mon Oct 28 07:24:51 UTC 2019

Hi Chris,

Sorry if this reply is late.

The method has been like this from the beginning. The alternative format you suggested should also work and can avoid unnecessary array copy as you described. However, as I understand the method should not be called often so you won't see much performance improvement.

In fact, I tend to believe that generatedSeed() should not belong to SecureRandom at all. A random generator can be seeded or re-seeded but it's not clear how it can generate seed itself. I think no PRNG or DRBG algorithms define that function. It will be nice if we have a new interface named SeedGenerator (or maybe more formally, EntropySource) that is able to generate seed. For this reason, I'm hesitated to suggest any enhancement to the existing SecureRandom::generateSeed method now.


p.s. Next time you can write to security-dev at on such topics.

> On Oct 16, 2019, at 11:22 AM, Chris Hennick <chrishennick1 at> wrote:
> While working on BetterRandom <>
> tonight, I was reminded that a quirk of SecureRandom's API creates
> unnecessary garbage in my use case:
> public class SecureRandomSeedGenerator implements SeedGenerator, Serializable {
>  private final SecureRandom source;
>  @Override public void generateSeed(final byte[] output) {
>    System.arraycopy(source.generateSeed(output.length), 0, output, 0,
> output.length);
>  }
> }
> The garbage in this case is the original array returned by
> source.generateSeed(). SeedGenerator.generateSeed()'s only warm callsites
> when used as I recommend (which are
> are specifically designed to use existing array instances, so that
> reseeding produces the minimum of garbage.
> For the garbage creation to be eliminated, I believe
> source.generateSeed(output.length) would at least have to be inlined
> (recursing down into the SecureRandomSpi), followed by escape analysis.
> Even then, eliminating the arraycopy is probably somewhere around the
> bleeding edge of optimization (although the arrays are likely to be short,
> and often all the same length). It's worth noting that
> SeedGenerator.generateSeed() is likely to be trimorphic at the warm
> call-sites because of
> .
> Should SecureRandom maybe have an API that can write a seed to an existing
> byte array, garbagelessly when possible?
> Sincerely,
> Chris Hennick

More information about the jdk-dev mailing list