Predict the Seed of Javascript's Math.random

后端 未结 4 795
独厮守ぢ
独厮守ぢ 2020-12-17 23:34

Okay, so I\'m doing some research on how random numbers are generated with the Math.random method. So far I learned that it starts with a \"random\" seed, and that seed is p

相关标签:
4条回答
  • 2020-12-18 00:16

    I looked through the Rhino source code to find out which pseudo-random function they use. Apparently they fall back to the Math.random function defined in the Java standard library.

    The documentation for Math.random says:

    Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. Returned values are chosen pseudorandomly with (approximately) uniform distribution from that range.

    When this method is first called, it creates a single new pseudorandom-number generator, exactly as if by the expression

    new java.util.Random
    

    This new pseudorandom-number generator is used thereafter for all calls to this method and is used nowhere else.

    This method is properly synchronized to allow correct use by more than one thread. However, if many threads need to generate pseudorandom numbers at a great rate, it may reduce contention for each thread to have its own pseudorandom-number generator.

    So I checked the documentation for java.util.Random and found this (for the default constructor):

    Creates a new random number generator. Its seed is initialized to a value based on the current time:

    public Random() { this(System.currentTimeMillis()); }
    

    Two Random objects created within the same millisecond will have the same sequence of random numbers.

    So now we know for sure that the seed is the current time in milliseconds. Also, the documentation for the second constructor says:

    Creates a new random number generator using a single long seed:

    public Random(long seed) { setSeed(seed); }
    

    Used by method next to hold the state of the pseudorandom number generator.

    The documentation for the setSeed method says:

    Sets the seed of this random number generator using a single long seed. The general contract of setSeed is that it alters the state of this random number generator object so as to be in exactly the same state as if it had just been created with the argument seed as a seed. The method setSeed is implemented by class Random as follows:

    synchronized public void setSeed(long seed) {
        this.seed = (seed ^ 0x5DEECE66DL) & ((1L << 48) - 1);
        haveNextNextGaussian = false;
    }
    

    The implementation of setSeed by class Random happens to use only 48 bits of the given seed. In general, however, an overriding method may use all 64 bits of the long argument as a seed value. Note: Although the seed value is an AtomicLong, this method must still be synchronized to ensure correct semantics of haveNextNextGaussian.

    The actual method used to generate the random number is nextDouble:

    Returns the next pseudorandom, uniformly distributed double value between 0.0 and 1.0 from this random number generator's sequence.

    The implementation of the nextDouble function is as follows:

    public double nextDouble() {
        return (((long)next(26) << 27) + next(27))
            / (double)(1L << 53);
    }
    

    Clearly it depends on the next function:

    Generates the next pseudorandom number. Subclass should override this, as this is used by all other methods.

    The implementation of the next function is as follows:

    synchronized protected int next(int bits) {
        seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1);
        return (int)(seed >>> (48 - bits));
    }
    

    That's the pseudo-random function you are looking for. As it's said in the documentation:

    This is a linear congruential pseudorandom number generator, as defined by D. H. Lehmer and described by Donald E. Knuth in The Art of Computer Programming, Volume 2: Seminumerical Algorithms, section 3.2.1.

    Note however that this is only the random number generator used by Rhino. Other implementations like Spidermonkey and V8 may have their own pseudo-random number generators.

    0 讨论(0)
  • 2020-12-18 00:16

    it's likely that there's more to the seed than the millisecond count, because you can call Math.random() many times in the same millisecond and it will return a different value each time.

    for (var i = 0; i < 3; i++) {
        console.log(Math.random(), (new Date()).getTime());
    };
    

    My output:

    0.0617244818713516 1352433709108
    0.8024995378218591 1352433709108
    0.2409922298975289 1352433709108
    

    If I were implementing it I might make the initial seed based on a millisecond count, and then add 1 each time it's called, so that you wouldn't get the same seed value twice.

    Here's a 100% accurate way of predicting the output from Math.random():

    Math.random = function () { return .5; };
    

    Now Math.random() will always return .5.

    0 讨论(0)
  • 2020-12-18 00:19

    The seed is a numeric value, so my guess is that it would be what you get if you call Date.now() (or new Date().getTime() for older browsers).

    However, I'm not sure when that seed is taken, or if the seed is isolated to the current page or common to the entire browser process. Predicting random numbers is supposed to be very hard or impossible, that's the whole point of them being random.

    0 讨论(0)
  • 2020-12-18 00:35

    No, you cannot predict the seed, but you can preemtively generate enough numbers in order to accurately brute force a match.

    Anyhow, start of by reading the wiki page on RNG's - http://en.wikipedia.org/wiki/Random_number_generation, the look at the practical implementations of PRNG's.

    0 讨论(0)
提交回复
热议问题