michael@0: // seedrandom.js version 2.1.
michael@0: // Author: David Bau
michael@0: // Date: 2013 Mar 16
michael@0: //
michael@0: // Defines a method Math.seedrandom() that, when called, substitutes
michael@0: // an explicitly seeded RC4-based algorithm for Math.random(). Also
michael@0: // supports automatic seeding from local or network sources of entropy.
michael@0: //
michael@0: // http://davidbau.com/encode/seedrandom.js
michael@0: // http://davidbau.com/encode/seedrandom-min.js
michael@0: //
michael@0: // Usage:
michael@0: //
michael@0: //
michael@0: //
michael@0: // Math.seedrandom('yay.'); Sets Math.random to a function that is
michael@0: // initialized using the given explicit seed.
michael@0: //
michael@0: // Math.seedrandom(); Sets Math.random to a function that is
michael@0: // seeded using the current time, dom state,
michael@0: // and other accumulated local entropy.
michael@0: // The generated seed string is returned.
michael@0: //
michael@0: // Math.seedrandom('yowza.', true);
michael@0: // Seeds using the given explicit seed mixed
michael@0: // together with accumulated entropy.
michael@0: //
michael@0: // Seeds using urandom bits from a server.
michael@0: //
michael@0: // More advanced examples:
michael@0: //
michael@0: // Math.seedrandom("hello."); // Use "hello." as the seed.
michael@0: // document.write(Math.random()); // Always 0.9282578795792454
michael@0: // document.write(Math.random()); // Always 0.3752569768646784
michael@0: // var rng1 = Math.random; // Remember the current prng.
michael@0: //
michael@0: // var autoseed = Math.seedrandom(); // New prng with an automatic seed.
michael@0: // document.write(Math.random()); // Pretty much unpredictable x.
michael@0: //
michael@0: // Math.random = rng1; // Continue "hello." prng sequence.
michael@0: // document.write(Math.random()); // Always 0.7316977468919549
michael@0: //
michael@0: // Math.seedrandom(autoseed); // Restart at the previous seed.
michael@0: // document.write(Math.random()); // Repeat the 'unpredictable' x.
michael@0: //
michael@0: // function reseed(event, count) { // Define a custom entropy collector.
michael@0: // var t = [];
michael@0: // function w(e) {
michael@0: // t.push([e.pageX, e.pageY, +new Date]);
michael@0: // if (t.length < count) { return; }
michael@0: // document.removeEventListener(event, w);
michael@0: // Math.seedrandom(t, true); // Mix in any previous entropy.
michael@0: // }
michael@0: // document.addEventListener(event, w);
michael@0: // }
michael@0: // reseed('mousemove', 100); // Reseed after 100 mouse moves.
michael@0: //
michael@0: // Version notes:
michael@0: //
michael@0: // The random number sequence is the same as version 1.0 for string seeds.
michael@0: // Version 2.0 changed the sequence for non-string seeds.
michael@0: // Version 2.1 speeds seeding and uses window.crypto to autoseed if present.
michael@0: //
michael@0: // The standard ARC4 key scheduler cycles short keys, which means that
michael@0: // seedrandom('ab') is equivalent to seedrandom('abab') and 'ababab'.
michael@0: // Therefore it is a good idea to add a terminator to avoid trivial
michael@0: // equivalences on short string seeds, e.g., Math.seedrandom(str + '\0').
michael@0: // Starting with version 2.0, a terminator is added automatically for
michael@0: // non-string seeds, so seeding with the number 111 is the same as seeding
michael@0: // with '111\0'.
michael@0: //
michael@0: // When seedrandom() is called with zero args, it uses a seed
michael@0: // drawn from the browser crypto object if present. If there is no
michael@0: // crypto support, seedrandom() uses the current time, the native rng,
michael@0: // and a walk of several DOM objects to collect a few bits of entropy.
michael@0: //
michael@0: // Each time the one- or two-argument forms of seedrandom are called,
michael@0: // entropy from the passed seed is accumulated in a pool to help generate
michael@0: // future seeds for the zero- and two-argument forms of seedrandom.
michael@0: //
michael@0: // On speed - This javascript implementation of Math.random() is about
michael@0: // 3-10x slower than the built-in Math.random() because it is not native
michael@0: // code, but that is typically fast enough. Some details (timings on
michael@0: // Chrome 25 on a 2010 vintage macbook):
michael@0: //
michael@0: // seeded Math.random() - avg less than 0.0002 milliseconds per call
michael@0: // seedrandom('explicit.') - avg less than 0.2 milliseconds per call
michael@0: // seedrandom('explicit.', true) - avg less than 0.2 milliseconds per call
michael@0: // seedrandom() with crypto - avg less than 0.2 milliseconds per call
michael@0: // seedrandom() without crypto - avg about 12 milliseconds per call
michael@0: //
michael@0: // On a 2012 windows 7 1.5ghz i5 laptop, Chrome, Firefox 19, IE 10, and
michael@0: // Opera have similarly fast timings. Slowest numbers are on Opera, with
michael@0: // about 0.0005 milliseconds per seeded Math.random() and 15 milliseconds
michael@0: // for autoseeding.
michael@0: //
michael@0: // LICENSE (BSD):
michael@0: //
michael@0: // Copyright 2013 David Bau, all rights reserved.
michael@0: //
michael@0: // Redistribution and use in source and binary forms, with or without
michael@0: // modification, are permitted provided that the following conditions are met:
michael@0: //
michael@0: // 1. Redistributions of source code must retain the above copyright
michael@0: // notice, this list of conditions and the following disclaimer.
michael@0: //
michael@0: // 2. Redistributions in binary form must reproduce the above copyright
michael@0: // notice, this list of conditions and the following disclaimer in the
michael@0: // documentation and/or other materials provided with the distribution.
michael@0: //
michael@0: // 3. Neither the name of this module nor the names of its contributors may
michael@0: // be used to endorse or promote products derived from this software
michael@0: // without specific prior written permission.
michael@0: //
michael@0: // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
michael@0: // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
michael@0: // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
michael@0: // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
michael@0: // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
michael@0: // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
michael@0: // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
michael@0: // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
michael@0: // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
michael@0: // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
michael@0: // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
michael@0: //
michael@0: /**
michael@0: * All code is in an anonymous closure to keep the global namespace clean.
michael@0: */
michael@0: (function (
michael@0: global, pool, math, width, chunks, digits) {
michael@0:
michael@0: //
michael@0: // The following constants are related to IEEE 754 limits.
michael@0: //
michael@0: var startdenom = math.pow(width, chunks),
michael@0: significance = math.pow(2, digits),
michael@0: overflow = significance * 2,
michael@0: mask = width - 1;
michael@0:
michael@0: //
michael@0: // seedrandom()
michael@0: // This is the seedrandom function described above.
michael@0: //
michael@0: math['seedrandom'] = function(seed, use_entropy) {
michael@0: var key = [];
michael@0:
michael@0: // Flatten the seed string or build one from local entropy if needed.
michael@0: var shortseed = mixkey(flatten(
michael@0: use_entropy ? [seed, tostring(pool)] :
michael@0: 0 in arguments ? seed : autoseed(), 3), key);
michael@0:
michael@0: // Use the seed to initialize an ARC4 generator.
michael@0: var arc4 = new ARC4(key);
michael@0:
michael@0: // Mix the randomness into accumulated entropy.
michael@0: mixkey(tostring(arc4.S), pool);
michael@0:
michael@0: // Override Math.random
michael@0:
michael@0: // This function returns a random double in [0, 1) that contains
michael@0: // randomness in every bit of the mantissa of the IEEE 754 value.
michael@0:
michael@0: math['random'] = function() { // Closure to return a random double:
michael@0: var n = arc4.g(chunks), // Start with a numerator n < 2 ^ 48
michael@0: d = startdenom, // and denominator d = 2 ^ 48.
michael@0: x = 0; // and no 'extra last byte'.
michael@0: while (n < significance) { // Fill up all significant digits by
michael@0: n = (n + x) * width; // shifting numerator and
michael@0: d *= width; // denominator and generating a
michael@0: x = arc4.g(1); // new least-significant-byte.
michael@0: }
michael@0: while (n >= overflow) { // To avoid rounding up, before adding
michael@0: n /= 2; // last byte, shift everything
michael@0: d /= 2; // right using integer math until
michael@0: x >>>= 1; // we have exactly the desired bits.
michael@0: }
michael@0: return (n + x) / d; // Form the number within [0, 1).
michael@0: };
michael@0:
michael@0: // Return the seed that was used
michael@0: return shortseed;
michael@0: };
michael@0:
michael@0: //
michael@0: // ARC4
michael@0: //
michael@0: // An ARC4 implementation. The constructor takes a key in the form of
michael@0: // an array of at most (width) integers that should be 0 <= x < (width).
michael@0: //
michael@0: // The g(count) method returns a pseudorandom integer that concatenates
michael@0: // the next (count) outputs from ARC4. Its return value is a number x
michael@0: // that is in the range 0 <= x < (width ^ count).
michael@0: //
michael@0: /** @constructor */
michael@0: function ARC4(key) {
michael@0: var t, keylen = key.length,
michael@0: me = this, i = 0, j = me.i = me.j = 0, s = me.S = [];
michael@0:
michael@0: // The empty key [] is treated as [0].
michael@0: if (!keylen) { key = [keylen++]; }
michael@0:
michael@0: // Set up S using the standard key scheduling algorithm.
michael@0: while (i < width) {
michael@0: s[i] = i++;
michael@0: }
michael@0: for (i = 0; i < width; i++) {
michael@0: s[i] = s[j = mask & (j + key[i % keylen] + (t = s[i]))];
michael@0: s[j] = t;
michael@0: }
michael@0:
michael@0: // The "g" method returns the next (count) outputs as one number.
michael@0: (me.g = function(count) {
michael@0: // Using instance members instead of closure state nearly doubles speed.
michael@0: var t, r = 0,
michael@0: i = me.i, j = me.j, s = me.S;
michael@0: while (count--) {
michael@0: t = s[i = mask & (i + 1)];
michael@0: r = r * width + s[mask & ((s[i] = s[j = mask & (j + t)]) + (s[j] = t))];
michael@0: }
michael@0: me.i = i; me.j = j;
michael@0: return r;
michael@0: // For robust unpredictability discard an initial batch of values.
michael@0: // See http://www.rsa.com/rsalabs/node.asp?id=2009
michael@0: })(width);
michael@0: }
michael@0:
michael@0: //
michael@0: // flatten()
michael@0: // Converts an object tree to nested arrays of strings.
michael@0: //
michael@0: function flatten(obj, depth) {
michael@0: var result = [], typ = (typeof obj)[0], prop;
michael@0: if (depth && typ == 'o') {
michael@0: for (prop in obj) {
michael@0: if (obj.hasOwnProperty(prop)) {
michael@0: try { result.push(flatten(obj[prop], depth - 1)); } catch (e) {}
michael@0: }
michael@0: }
michael@0: }
michael@0: return (result.length ? result : typ == 's' ? obj : obj + '\0');
michael@0: }
michael@0:
michael@0: //
michael@0: // mixkey()
michael@0: // Mixes a string seed into a key that is an array of integers, and
michael@0: // returns a shortened string seed that is equivalent to the result key.
michael@0: //
michael@0: function mixkey(seed, key) {
michael@0: var stringseed = seed + '', smear, j = 0;
michael@0: while (j < stringseed.length) {
michael@0: key[mask & j] =
michael@0: mask & ((smear ^= key[mask & j] * 19) + stringseed.charCodeAt(j++));
michael@0: }
michael@0: return tostring(key);
michael@0: }
michael@0:
michael@0: //
michael@0: // autoseed()
michael@0: // Returns an object for autoseeding, using window.crypto if available.
michael@0: //
michael@0: /** @param {Uint8Array=} seed */
michael@0: function autoseed(seed) {
michael@0: try {
michael@0: global.crypto.getRandomValues(seed = new Uint8Array(width));
michael@0: return tostring(seed);
michael@0: } catch (e) {
michael@0: return [+new Date, global.document, global.history,
michael@0: global.navigator, global.screen, tostring(pool)];
michael@0: }
michael@0: }
michael@0:
michael@0: //
michael@0: // tostring()
michael@0: // Converts an array of charcodes to a string
michael@0: //
michael@0: function tostring(a) {
michael@0: return String.fromCharCode.apply(0, a);
michael@0: }
michael@0:
michael@0: //
michael@0: // When seedrandom.js is loaded, we immediately mix a few bits
michael@0: // from the built-in RNG into the entropy pool. Because we do
michael@0: // not want to intefere with determinstic PRNG state later,
michael@0: // seedrandom will not call math.random on its own again after
michael@0: // initialization.
michael@0: //
michael@0: mixkey(math.random(), pool);
michael@0:
michael@0: // End anonymous scope, and pass initial values.
michael@0: })(
michael@0: this, // global window object
michael@0: [], // pool: entropy pool starts empty
michael@0: Math, // math: package containing random, pow, and seedrandom
michael@0: 256, // width: each RC4 output is 0 <= x < 256
michael@0: 6, // chunks: at least six RC4 outputs for each double
michael@0: 52 // digits: there are 52 significant digits in a double
michael@0: );