SecureRandom.generateSeed() and unnecessary garbage

Weijun Wang weijun.wang at oracle.com
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.

Thanks,
Max

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

> On Oct 16, 2019, at 11:22 AM, Chris Hennick <chrishennick1 at gmail.com> wrote:
> 
> While working on BetterRandom <https://github.com/Pr0methean/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
> https://github.com/Pr0methean/BetterRandom/blob/bdd596d25497776156b8c87ab749e00c8b2b8bd0/betterrandom/src/main/java/io/github/pr0methean/betterrandom/seed/RandomSeederThread.java#L226)
> 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
> https://github.com/Pr0methean/BetterRandom/blob/6df10c5b6e8ec24dea4275bf2b487dd9aecdc369/betterrandom/src/main/java/io/github/pr0methean/betterrandom/seed/DefaultSeedGenerator.java#L42-L45
> .
> 
> 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