Advertisement
Guest User

Untitled

a guest
Dec 16th, 2019
761
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  
  3. seedrandom.js
  4. =============
  5.  
  6. Seeded random number generator for Javascript.
  7.  
  8. version 2.3.10
  9. Author: David Bau
  10. Date: 2014 Sep 20
  11.  
  12. Can be used as a plain script, a node.js module or an AMD module.
  13.  
  14. Script tag usage
  15. ----------------
  16.  
  17. <script src=//cdnjs.cloudflare.com/ajax/libs/seedrandom/2.3.10/seedrandom.min.js>
  18. </script>
  19.  
  20. // Sets Math.random to a PRNG initialized using the given explicit seed.
  21. Math.seedrandom('hello.');
  22. console.log(Math.random());          // Always 0.9282578795792454
  23. console.log(Math.random());          // Always 0.3752569768646784
  24.  
  25. // Sets Math.random to an ARC4-based PRNG that is autoseeded using the
  26. // current time, dom state, and other accumulated local entropy.
  27. // The generated seed string is returned.
  28. Math.seedrandom();
  29. console.log(Math.random());          // Reasonably unpredictable.
  30.  
  31. // Seeds using the given explicit seed mixed with accumulated entropy.
  32. Math.seedrandom('added entropy.', { entropy: true });
  33. console.log(Math.random());          // As unpredictable as added entropy.
  34.  
  35. // Use "new" to create a local prng without altering Math.random.
  36. var myrng = new Math.seedrandom('hello.');
  37. console.log(myrng());                // Always 0.9282578795792454
  38.  
  39.  
  40. Node.js usage
  41. -------------
  42.  
  43. npm install seedrandom
  44.  
  45. // Local PRNG: does not affect Math.random.
  46. var seedrandom = require('seedrandom');
  47. var rng = seedrandom('hello.');
  48. console.log(rng());                  // Always 0.9282578795792454
  49.  
  50. // Autoseeded ARC4-based PRNG.
  51. rng = seedrandom();
  52. console.log(rng());                  // Reasonably unpredictable.
  53.  
  54. // Global PRNG: set Math.random.
  55. seedrandom('hello.', { global: true });
  56. console.log(Math.random());          // Always 0.9282578795792454
  57.  
  58. // Mixing accumulated entropy.
  59. rng = seedrandom('added entropy.', { entropy: true });
  60. console.log(rng());                  // As unpredictable as added entropy.
  61.  
  62.  
  63. Require.js usage
  64. ----------------
  65.  
  66. Similar to node.js usage:
  67.  
  68. bower install seedrandom
  69.  
  70. require(['seedrandom'], function(seedrandom) {
  71.   var rng = seedrandom('hello.');
  72.   console.log(rng());                  // Always 0.9282578795792454
  73. });
  74.  
  75.  
  76. Network seeding
  77. ---------------
  78.  
  79. <script src=//cdnjs.cloudflare.com/ajax/libs/seedrandom/2.3.10/seedrandom.min.js>
  80. </script>
  81.  
  82. <!-- Seeds using urandom bits from a server. -->
  83. <script src=//jsonlib.appspot.com/urandom?callback=Math.seedrandom">
  84. </script>
  85.  
  86. <!-- Seeds mixing in random.org bits -->
  87. <script>
  88. (function(x, u, s){
  89.   try {
  90.     // Make a synchronous request to random.org.
  91.     x.open('GET', u, false);
  92.     x.send();
  93.     s = unescape(x.response.trim().replace(/^|\s/g, '%'));
  94.   } finally {
  95.     // Seed with the response, or autoseed on failure.
  96.     Math.seedrandom(s, !!s);
  97.   }
  98. })(new XMLHttpRequest, 'https://www.random.org/integers/' +
  99.   '?num=256&min=0&max=255&col=1&base=16&format=plain&rnd=new');
  100. </script>
  101.  
  102. Reseeding using user input
  103. --------------------------
  104.  
  105. var seed = Math.seedrandom();        // Use prng with an automatic seed.
  106. document.write(Math.random());       // Pretty much unpredictable x.
  107.  
  108. var rng = new Math.seedrandom(seed); // A new prng with the same seed.
  109. document.write(rng());               // Repeat the 'unpredictable' x.
  110.  
  111. function reseed(event, count) {      // Define a custom entropy collector.
  112.   var t = [];
  113.   function w(e) {
  114.     t.push([e.pageX, e.pageY, +new Date]);
  115.     if (t.length &lt; count) { return; }
  116.     document.removeEventListener(event, w);
  117.     Math.seedrandom(t, { entropy: true });
  118.   }
  119.   document.addEventListener(event, w);
  120. }
  121. reseed('mousemove', 100);            // Reseed after 100 mouse moves.
  122.  
  123. The "pass" option can be used to get both the prng and the seed.
  124. The following returns both an autoseeded prng and the seed as an object,
  125. without mutating Math.random:
  126.  
  127. var obj = Math.seedrandom(null, { pass: function(prng, seed) {
  128.   return { random: prng, seed: seed };
  129. }});
  130.  
  131.  
  132. Version notes
  133. -------------
  134.  
  135. The random number sequence is the same as version 1.0 for string seeds.
  136. * Version 2.0 changed the sequence for non-string seeds.
  137. * Version 2.1 speeds seeding and uses window.crypto to autoseed if present.
  138. * Version 2.2 alters non-crypto autoseeding to sweep up entropy from plugins.
  139. * Version 2.3 adds support for "new", module loading, and a null seed arg.
  140. * Version 2.3.1 adds a build environment, module packaging, and tests.
  141. * Version 2.3.4 fixes bugs on IE8, and switches to MIT license.
  142. * Version 2.3.6 adds a readable options object argument.
  143. * Version 2.3.10 adds support for node.js crypto (contributed by ctd1500).
  144.  
  145. The standard ARC4 key scheduler cycles short keys, which means that
  146. seedrandom('ab') is equivalent to seedrandom('abab') and 'ababab'.
  147. Therefore it is a good idea to add a terminator to avoid trivial
  148. equivalences on short string seeds, e.g., Math.seedrandom(str + '\0').
  149. Starting with version 2.0, a terminator is added automatically for
  150. non-string seeds, so seeding with the number 111 is the same as seeding
  151. with '111\0'.
  152.  
  153. When seedrandom() is called with zero args or a null seed, it uses a
  154. seed drawn from the browser crypto object if present.  If there is no
  155. crypto support, seedrandom() uses the current time, the native rng,
  156. and a walk of several DOM objects to collect a few bits of entropy.
  157.  
  158. Each time the one- or two-argument forms of seedrandom are called,
  159. entropy from the passed seed is accumulated in a pool to help generate
  160. future seeds for the zero- and two-argument forms of seedrandom.
  161.  
  162. On speed - This javascript implementation of Math.random() is several
  163. times slower than the built-in Math.random() because it is not native
  164. code, but that is typically fast enough.  Some details (timings on
  165. Chrome 25 on a 2010 vintage macbook):
  166.  
  167. * seeded Math.random()          - avg less than 0.0002 milliseconds per call
  168. * seedrandom('explicit.')       - avg less than 0.2 milliseconds per call
  169. * seedrandom('explicit.', true) - avg less than 0.2 milliseconds per call
  170. * seedrandom() with crypto      - avg less than 0.2 milliseconds per call
  171.  
  172. Autoseeding without crypto is somewhat slower, about 20-30 milliseconds on
  173. a 2012 windows 7 1.5ghz i5 laptop, as seen on Firefox 19, IE 10, and Opera.
  174. Seeded rng calls themselves are fast across these browsers, with slowest
  175. numbers on Opera at about 0.0005 ms per seeded Math.random().
  176.  
  177.  
  178. LICENSE (MIT)
  179. -------------
  180.  
  181. Copyright 2014 David Bau.
  182.  
  183. Permission is hereby granted, free of charge, to any person obtaining
  184. a copy of this software and associated documentation files (the
  185. "Software"), to deal in the Software without restriction, including
  186. without limitation the rights to use, copy, modify, merge, publish,
  187. distribute, sublicense, and/or sell copies of the Software, and to
  188. permit persons to whom the Software is furnished to do so, subject to
  189. the following conditions:
  190.  
  191. The above copyright notice and this permission notice shall be
  192. included in all copies or substantial portions of the Software.
  193.  
  194. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  195. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  196. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  197. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  198. CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  199. TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  200. SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  201.  
  202. */
  203.  
  204. /**
  205.  * All code is in an anonymous closure to keep the global namespace clean.
  206.  */
  207. (function (
  208.     global, pool, math, width, chunks, digits, module, define, rngname) {
  209.  
  210. //
  211. // The following constants are related to IEEE 754 limits.
  212. //
  213. var startdenom = math.pow(width, chunks),
  214.     significance = math.pow(2, digits),
  215.     overflow = significance * 2,
  216.     mask = width - 1,
  217.     nodecrypto;
  218.  
  219. //
  220. // seedrandom()
  221. // This is the seedrandom function described above.
  222. //
  223. var impl = math['seed' + rngname] = function(seed, options, callback) {
  224.   var key = [];
  225.   options = (options == true) ? { entropy: true } : (options || {});
  226.  
  227.   // Flatten the seed string or build one from local entropy if needed.
  228.   var shortseed = mixkey(flatten(
  229.     options.entropy ? [seed, tostring(pool)] :
  230.     (seed == null) ? autoseed() : seed, 3), key);
  231.  
  232.   // Use the seed to initialize an ARC4 generator.
  233.   var arc4 = new ARC4(key);
  234.  
  235.   // Mix the randomness into accumulated entropy.
  236.   mixkey(tostring(arc4.S), pool);
  237.  
  238.   // Calling convention: what to return as a function of prng, seed, is_math.
  239.   return (options.pass || callback ||
  240.       // If called as a method of Math (Math.seedrandom()), mutate Math.random
  241.       // because that is how seedrandom.js has worked since v1.0.  Otherwise,
  242.       // it is a newer calling convention, so return the prng directly.
  243.       function(prng, seed, is_math_call) {
  244.         if (is_math_call) { math[rngname] = prng; return seed; }
  245.         else return prng;
  246.       })(
  247.  
  248.   // This function returns a random double in [0, 1) that contains
  249.   // randomness in every bit of the mantissa of the IEEE 754 value.
  250.   function() {
  251.     var n = arc4.g(chunks),             // Start with a numerator n < 2 ^ 48
  252.         d = startdenom,                 //   and denominator d = 2 ^ 48.
  253.         x = 0;                          //   and no 'extra last byte'.
  254.     while (n < significance) {          // Fill up all significant digits by
  255.       n = (n + x) * width;              //   shifting numerator and
  256.       d *= width;                       //   denominator and generating a
  257.       x = arc4.g(1);                    //   new least-significant-byte.
  258.     }
  259.     while (n >= overflow) {             // To avoid rounding up, before adding
  260.       n /= 2;                           //   last byte, shift everything
  261.       d /= 2;                           //   right using integer math until
  262.       x >>>= 1;                         //   we have exactly the desired bits.
  263.     }
  264.     return (n + x) / d;                 // Form the number within [0, 1).
  265.   }, shortseed, 'global' in options ? options.global : (this == math));
  266. };
  267.  
  268. //
  269. // ARC4
  270. //
  271. // An ARC4 implementation.  The constructor takes a key in the form of
  272. // an array of at most (width) integers that should be 0 <= x < (width).
  273. //
  274. // The g(count) method returns a pseudorandom integer that concatenates
  275. // the next (count) outputs from ARC4.  Its return value is a number x
  276. // that is in the range 0 <= x < (width ^ count).
  277. //
  278. /** @constructor */
  279. function ARC4(key) {
  280.   var t, keylen = key.length,
  281.       me = this, i = 0, j = me.i = me.j = 0, s = me.S = [];
  282.  
  283.   // The empty key [] is treated as [0].
  284.   if (!keylen) { key = [keylen++]; }
  285.  
  286.   // Set up S using the standard key scheduling algorithm.
  287.   while (i < width) {
  288.     s[i] = i++;
  289.   }
  290.   for (i = 0; i < width; i++) {
  291.     s[i] = s[j = mask & (j + key[i % keylen] + (t = s[i]))];
  292.     s[j] = t;
  293.   }
  294.  
  295.   // The "g" method returns the next (count) outputs as one number.
  296.   (me.g = function(count) {
  297.     // Using instance members instead of closure state nearly doubles speed.
  298.     var t, r = 0,
  299.         i = me.i, j = me.j, s = me.S;
  300.     while (count--) {
  301.       t = s[i = mask & (i + 1)];
  302.       r = r * width + s[mask & ((s[i] = s[j = mask & (j + t)]) + (s[j] = t))];
  303.     }
  304.     me.i = i; me.j = j;
  305.     return r;
  306.     // For robust unpredictability, the function call below automatically
  307.     // discards an initial batch of values.  This is called RC4-drop[256].
  308.     // See http://google.com/search?q=rsa+fluhrer+response&btnI
  309.   })(width);
  310. }
  311.  
  312. //
  313. // flatten()
  314. // Converts an object tree to nested arrays of strings.
  315. //
  316. function flatten(obj, depth) {
  317.   var result = [], typ = (typeof obj), prop;
  318.   if (depth && typ == 'object') {
  319.     for (prop in obj) {
  320.       try { result.push(flatten(obj[prop], depth - 1)); } catch (e) {}
  321.     }
  322.   }
  323.   return (result.length ? result : typ == 'string' ? obj : obj + '\0');
  324. }
  325.  
  326. //
  327. // mixkey()
  328. // Mixes a string seed into a key that is an array of integers, and
  329. // returns a shortened string seed that is equivalent to the result key.
  330. //
  331. function mixkey(seed, key) {
  332.   var stringseed = seed + '', smear, j = 0;
  333.   while (j < stringseed.length) {
  334.     key[mask & j] =
  335.       mask & ((smear ^= key[mask & j] * 19) + stringseed.charCodeAt(j++));
  336.   }
  337.   return tostring(key);
  338. }
  339.  
  340. //
  341. // autoseed()
  342. // Returns an object for autoseeding, using window.crypto if available.
  343. //
  344. /** @param {Uint8Array|Navigator=} seed */
  345. function autoseed(seed) {
  346.   try {
  347.     if (nodecrypto) return tostring(nodecrypto.randomBytes(width));
  348.     global.crypto.getRandomValues(seed = new Uint8Array(width));
  349.     return tostring(seed);
  350.   } catch (e) {
  351.     return [+new Date, global, (seed = global.navigator) && seed.plugins,
  352.       global.screen, tostring(pool)];
  353.   }
  354. }
  355.  
  356. //
  357. // tostring()
  358. // Converts an array of charcodes to a string
  359. //
  360. function tostring(a) {
  361.   return String.fromCharCode.apply(0, a);
  362. }
  363.  
  364. //
  365. // When seedrandom.js is loaded, we immediately mix a few bits
  366. // from the built-in RNG into the entropy pool.  Because we do
  367. // not want to interfere with deterministic PRNG state later,
  368. // seedrandom will not call math.random on its own again after
  369. // initialization.
  370. //
  371. mixkey(math[rngname](), pool);
  372.  
  373. //
  374. // Nodejs and AMD support: export the implementation as a module using
  375. // either convention.
  376. //
  377. if (module && module.exports) {
  378.   module.exports = impl;
  379.   try {
  380.     // When in node.js, try using crypto package for autoseeding.
  381.     nodecrypto = require('crypto');
  382.   } catch (ex) {}
  383. } else if (define && define.amd) {
  384.   define(function() { return impl; });
  385. }
  386.  
  387. //
  388. // Node.js native crypto support.
  389. //
  390.  
  391. // End anonymous scope, and pass initial values.
  392. })(
  393.   this,   // global window object
  394.   [],     // pool: entropy pool starts empty
  395.   Math,   // math: package containing random, pow, and seedrandom
  396.   256,    // width: each RC4 output is 0 <= x < 256
  397.   6,      // chunks: at least six RC4 outputs for each double
  398.   52,     // digits: there are 52 significant digits in a double
  399.   (typeof module) == 'object' && module,    // present in node.js
  400.   (typeof define) == 'function' && define,  // present with an AMD loader
  401.   'random'// rngname: name for Math.random and Math.seedrandom
  402. );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement