PageRenderTime 46ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/ajax/libs/seedrandom/2.3.9/seedrandom.js

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