Is there a way to generate a seed out of a sequence of numbers?

前端 未结 5 981
北荒
北荒 2021-01-02 04:59

For example if java produces the pseudorandom sequence: 9 3 2 5 6 by using 23 as a seed, how can I do the inverse? i.e. getting 23<

5条回答
  •  伪装坚强ぢ
    2021-01-02 05:41

    It is certainly possible to recover the seed used by java.util.Random. This post describes the math behind Random's linear congruential formula, and here is a function to discover the current seed from the last two integers returned from nextInt().

    public static long getCurrentSeed(int i1, int i2) {
            final long multiplier = 0x5DEECE66DL;
            final long inv_mult = 0xDFE05BCB1365L;
            final long increment = 0xBL;
            final long mask = ((1L << 48) - 1);
    
            long suffix = 0L;
            long lastSeed;
            long currSeed;
            int lastInt;
    
            for (long i=0; i < (1<<16); i++) {
                    suffix = i;
                    currSeed = ((long)i2 << 16) | suffix;
                    lastSeed = ((currSeed - increment) * inv_mult) & mask;
                    lastInt = (int)(lastSeed >>> 16);
    
                    if (lastInt == i1) {
                            /* We've found the current seed, need to roll back 2 seeds */
                            currSeed = lastSeed;
                            lastSeed = ((currSeed - increment) * inv_mult) & mask;
                            return  lastSeed ^ multiplier;
                    }
            }
    
            /* Error, current seed not found */
            System.err.println("current seed not found");
            return 0;
    }
    

    This function returns a value that can be used with rand.setSeed() to generate a pseudorandom sequence of numbers starting with i1 and i2.

提交回复
热议问题