jeudi 6 mai 2021

Determistic random numbers with multiple instances of SecureRandom [duplicate]

I am currently working on a project where I need to generate some random numbers and validate them later on using the same seed. I would like to achieve this with SecureRandom because I want to seed the random generator directly with some byte array.

However, SecureRandom does not behave like I would expect it to. When I create two instances of Random with the same seed I get the same long values when using nextLong(). This is what I want.

When I do the same thing with SecureRandom I get different results for each instance. I think this has something to do with the internal "state" of the random generator.

    var random1 = new Random(100);
    System.out.println(random1.nextLong()); //-5128016860359238732
    System.out.println(random1.nextLong()); // 3596673253889729385

    var random2 = new Random(100);
    System.out.println(random2.nextLong()); //-5128016860359238732
    System.out.println(random2.nextLong()); // 3596673253889729385

    var secureRandom1 = new SecureRandom(new byte[20]);
    System.out.println(secureRandom1.nextLong()); //5290194844706710024
    System.out.println(secureRandom1.nextLong()); //3079558514620206002
    
    var secureRandom2 = new SecureRandom(new byte[20]);
    System.out.println(secureRandom2.nextLong()); //-1296919875338532547
    System.out.println(secureRandom2.nextLong()); // 4506963961060072355

Is it somehow possible to configure SecureRandom to generate the same random longs when provided the same seed?




Aucun commentaire:

Enregistrer un commentaire