seedrandom.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. // seedrandom.js version 2.2.
  2. // Author: David Bau
  3. // Date: 2013 Jun 15
  4. //
  5. // Defines a method Math.seedrandom() that, when called, substitutes
  6. // an explicitly seeded RC4-based algorithm for Math.random(). Also
  7. // supports automatic seeding from local or network sources of entropy.
  8. //
  9. // http://davidbau.com/encode/seedrandom.js
  10. // http://davidbau.com/encode/seedrandom-min.js
  11. //
  12. // Usage:
  13. //
  14. // <script src=http://davidbau.com/encode/seedrandom-min.js></script>
  15. //
  16. // Math.seedrandom('yay.'); Sets Math.random to a function that is
  17. // initialized using the given explicit seed.
  18. //
  19. // Math.seedrandom(); Sets Math.random to a function that is
  20. // seeded using the current time, dom state,
  21. // and other accumulated local entropy.
  22. // The generated seed string is returned.
  23. //
  24. // Math.seedrandom('yowza.', true);
  25. // Seeds using the given explicit seed mixed
  26. // together with accumulated entropy.
  27. //
  28. // <script src="https://jsonlib.appspot.com/urandom?callback=Math.seedrandom">
  29. // </script> Seeds using urandom bits from a server.
  30. //
  31. // More advanced examples:
  32. //
  33. // Math.seedrandom("hello."); // Use "hello." as the seed.
  34. // document.write(Math.random()); // Always 0.9282578795792454
  35. // document.write(Math.random()); // Always 0.3752569768646784
  36. // var rng1 = Math.random; // Remember the current prng.
  37. //
  38. // var autoseed = Math.seedrandom(); // New prng with an automatic seed.
  39. // document.write(Math.random()); // Pretty much unpredictable x.
  40. //
  41. // Math.random = rng1; // Continue "hello." prng sequence.
  42. // document.write(Math.random()); // Always 0.7316977468919549
  43. //
  44. // Math.seedrandom(autoseed); // Restart at the previous seed.
  45. // document.write(Math.random()); // Repeat the 'unpredictable' x.
  46. //
  47. // function reseed(event, count) { // Define a custom entropy collector.
  48. // var t = [];
  49. // function w(e) {
  50. // t.push([e.pageX, e.pageY, +new Date]);
  51. // if (t.length < count) { return; }
  52. // document.removeEventListener(event, w);
  53. // Math.seedrandom(t, true); // Mix in any previous entropy.
  54. // }
  55. // document.addEventListener(event, w);
  56. // }
  57. // reseed('mousemove', 100); // Reseed after 100 mouse moves.
  58. //
  59. // Version notes:
  60. //
  61. // The random number sequence is the same as version 1.0 for string seeds.
  62. // Version 2.0 changed the sequence for non-string seeds.
  63. // Version 2.1 speeds seeding and uses window.crypto to autoseed if present.
  64. // Version 2.2 alters non-crypto autoseeding to sweep up entropy from plugins.
  65. //
  66. // The standard ARC4 key scheduler cycles short keys, which means that
  67. // seedrandom('ab') is equivalent to seedrandom('abab') and 'ababab'.
  68. // Therefore it is a good idea to add a terminator to avoid trivial
  69. // equivalences on short string seeds, e.g., Math.seedrandom(str + '\0').
  70. // Starting with version 2.0, a terminator is added automatically for
  71. // non-string seeds, so seeding with the number 111 is the same as seeding
  72. // with '111\0'.
  73. //
  74. // When seedrandom() is called with zero args, it uses a seed
  75. // drawn from the browser crypto object if present. If there is no
  76. // crypto support, seedrandom() uses the current time, the native rng,
  77. // and a walk of several DOM objects to collect a few bits of entropy.
  78. //
  79. // Each time the one- or two-argument forms of seedrandom are called,
  80. // entropy from the passed seed is accumulated in a pool to help generate
  81. // future seeds for the zero- and two-argument forms of seedrandom.
  82. //
  83. // On speed - This javascript implementation of Math.random() is about
  84. // 3-10x slower than the built-in Math.random() because it is not native
  85. // code, but that is typically fast enough. Some details (timings on
  86. // Chrome 25 on a 2010 vintage macbook):
  87. //
  88. // seeded Math.random() - avg less than 0.0002 milliseconds per call
  89. // seedrandom('explicit.') - avg less than 0.2 milliseconds per call
  90. // seedrandom('explicit.', true) - avg less than 0.2 milliseconds per call
  91. // seedrandom() with crypto - avg less than 0.2 milliseconds per call
  92. //
  93. // Autoseeding without crypto is somewhat slower, about 20-30 milliseconds on
  94. // a 2012 windows 7 1.5ghz i5 laptop, as seen on Firefox 19, IE 10, and Opera.
  95. // Seeded rng calls themselves are fast across these browsers, with slowest
  96. // numbers on Opera at about 0.0005 ms per seeded Math.random().
  97. //
  98. // LICENSE (BSD):
  99. //
  100. // Copyright 2013 David Bau, all rights reserved.
  101. //
  102. // Redistribution and use in source and binary forms, with or without
  103. // modification, are permitted provided that the following conditions are met:
  104. //
  105. // 1. Redistributions of source code must retain the above copyright
  106. // notice, this list of conditions and the following disclaimer.
  107. //
  108. // 2. Redistributions in binary form must reproduce the above copyright
  109. // notice, this list of conditions and the following disclaimer in the
  110. // documentation and/or other materials provided with the distribution.
  111. //
  112. // 3. Neither the name of this module nor the names of its contributors may
  113. // be used to endorse or promote products derived from this software
  114. // without specific prior written permission.
  115. //
  116. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  117. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  118. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  119. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  120. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  121. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  122. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  123. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  124. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  125. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  126. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  127. //
  128. /**
  129. * All code is in an anonymous closure to keep the global namespace clean.
  130. */
  131. (function (
  132. global, pool, math, width, chunks, digits) {
  133. //
  134. // The following constants are related to IEEE 754 limits.
  135. //
  136. var startdenom = math.pow(width, chunks),
  137. significance = math.pow(2, digits),
  138. overflow = significance * 2,
  139. mask = width - 1;
  140. //
  141. // seedrandom()
  142. // This is the seedrandom function described above.
  143. //
  144. math['seedrandom'] = function(seed, use_entropy) {
  145. var key = [];
  146. // Flatten the seed string or build one from local entropy if needed.
  147. var shortseed = mixkey(flatten(
  148. use_entropy ? [seed, tostring(pool)] :
  149. 0 in arguments ? seed : autoseed(), 3), key);
  150. // Use the seed to initialize an ARC4 generator.
  151. var arc4 = new ARC4(key);
  152. // Mix the randomness into accumulated entropy.
  153. mixkey(tostring(arc4.S), pool);
  154. // Override Math.random
  155. // This function returns a random double in [0, 1) that contains
  156. // randomness in every bit of the mantissa of the IEEE 754 value.
  157. math['random'] = function() { // Closure to return a random double:
  158. var n = arc4.g(chunks), // Start with a numerator n < 2 ^ 48
  159. d = startdenom, // and denominator d = 2 ^ 48.
  160. x = 0; // and no 'extra last byte'.
  161. while (n < significance) { // Fill up all significant digits by
  162. n = (n + x) * width; // shifting numerator and
  163. d *= width; // denominator and generating a
  164. x = arc4.g(1); // new least-significant-byte.
  165. }
  166. while (n >= overflow) { // To avoid rounding up, before adding
  167. n /= 2; // last byte, shift everything
  168. d /= 2; // right using integer math until
  169. x >>>= 1; // we have exactly the desired bits.
  170. }
  171. return (n + x) / d; // Form the number within [0, 1).
  172. };
  173. // Return the seed that was used
  174. return shortseed;
  175. };
  176. //
  177. // ARC4
  178. //
  179. // An ARC4 implementation. The constructor takes a key in the form of
  180. // an array of at most (width) integers that should be 0 <= x < (width).
  181. //
  182. // The g(count) method returns a pseudorandom integer that concatenates
  183. // the next (count) outputs from ARC4. Its return value is a number x
  184. // that is in the range 0 <= x < (width ^ count).
  185. //
  186. /** @constructor */
  187. function ARC4(key) {
  188. var t, keylen = key.length,
  189. me = this, i = 0, j = me.i = me.j = 0, s = me.S = [];
  190. // The empty key [] is treated as [0].
  191. if (!keylen) { key = [keylen++]; }
  192. // Set up S using the standard key scheduling algorithm.
  193. while (i < width) {
  194. s[i] = i++;
  195. }
  196. for (i = 0; i < width; i++) {
  197. s[i] = s[j = mask & (j + key[i % keylen] + (t = s[i]))];
  198. s[j] = t;
  199. }
  200. // The "g" method returns the next (count) outputs as one number.
  201. (me.g = function(count) {
  202. // Using instance members instead of closure state nearly doubles speed.
  203. var t, r = 0,
  204. i = me.i, j = me.j, s = me.S;
  205. while (count--) {
  206. t = s[i = mask & (i + 1)];
  207. r = r * width + s[mask & ((s[i] = s[j = mask & (j + t)]) + (s[j] = t))];
  208. }
  209. me.i = i; me.j = j;
  210. return r;
  211. // For robust unpredictability discard an initial batch of values.
  212. // See http://www.rsa.com/rsalabs/node.asp?id=2009
  213. })(width);
  214. }
  215. //
  216. // flatten()
  217. // Converts an object tree to nested arrays of strings.
  218. //
  219. function flatten(obj, depth) {
  220. var result = [], typ = (typeof obj)[0], prop;
  221. if (depth && typ == 'o') {
  222. for (prop in obj) {
  223. try { result.push(flatten(obj[prop], depth - 1)); } catch (e) {}
  224. }
  225. }
  226. return (result.length ? result : typ == 's' ? obj : obj + '\0');
  227. }
  228. //
  229. // mixkey()
  230. // Mixes a string seed into a key that is an array of integers, and
  231. // returns a shortened string seed that is equivalent to the result key.
  232. //
  233. function mixkey(seed, key) {
  234. var stringseed = seed + '', smear, j = 0;
  235. while (j < stringseed.length) {
  236. key[mask & j] =
  237. mask & ((smear ^= key[mask & j] * 19) + stringseed.charCodeAt(j++));
  238. }
  239. return tostring(key);
  240. }
  241. //
  242. // autoseed()
  243. // Returns an object for autoseeding, using window.crypto if available.
  244. //
  245. /** @param {Uint8Array=} seed */
  246. function autoseed(seed) {
  247. try {
  248. global.crypto.getRandomValues(seed = new Uint8Array(width));
  249. return tostring(seed);
  250. } catch (e) {
  251. return [+new Date, global, global.navigator.plugins,
  252. global.screen, tostring(pool)];
  253. }
  254. }
  255. //
  256. // tostring()
  257. // Converts an array of charcodes to a string
  258. //
  259. function tostring(a) {
  260. return String.fromCharCode.apply(0, a);
  261. }
  262. //
  263. // When seedrandom.js is loaded, we immediately mix a few bits
  264. // from the built-in RNG into the entropy pool. Because we do
  265. // not want to intefere with determinstic PRNG state later,
  266. // seedrandom will not call math.random on its own again after
  267. // initialization.
  268. //
  269. mixkey(math.random(), pool);
  270. // End anonymous scope, and pass initial values.
  271. })(
  272. this, // global window object
  273. [], // pool: entropy pool starts empty
  274. Math, // math: package containing random, pow, and seedrandom
  275. 256, // width: each RC4 output is 0 <= x < 256
  276. 6, // chunks: at least six RC4 outputs for each double
  277. 52 // digits: there are 52 significant digits in a double
  278. );