seedrandom.js 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. /*
  2. Copyright 2014 David Bau.
  3. Permission is hereby granted, free of charge, to any person obtaining
  4. a copy of this software and associated documentation files (the
  5. "Software"), to deal in the Software without restriction, including
  6. without limitation the rights to use, copy, modify, merge, publish,
  7. distribute, sublicense, and/or sell copies of the Software, and to
  8. permit persons to whom the Software is furnished to do so, subject to
  9. the following conditions:
  10. The above copyright notice and this permission notice shall be
  11. included in all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  13. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  14. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  15. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  16. CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  17. TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  18. SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  19. */
  20. (function (pool, math) {
  21. //
  22. // The following constants are related to IEEE 754 limits.
  23. //
  24. var global = this,
  25. width = 256, // each RC4 output is 0 <= x < 256
  26. chunks = 6, // at least six RC4 outputs for each double
  27. digits = 52, // there are 52 significant digits in a double
  28. rngname = 'random', // rngname: name for Math.random and Math.seedrandom
  29. startdenom = math.pow(width, chunks),
  30. significance = math.pow(2, digits),
  31. overflow = significance * 2,
  32. mask = width - 1,
  33. nodecrypto; // node.js crypto module, initialized at the bottom.
  34. //
  35. // seedrandom()
  36. // This is the seedrandom function described above.
  37. //
  38. function seedrandom(seed, options, callback) {
  39. var key = [];
  40. options = (options == true) ? { entropy: true } : (options || {});
  41. // Flatten the seed string or build one from local entropy if needed.
  42. var shortseed = mixkey(flatten(
  43. options.entropy ? [seed, tostring(pool)] :
  44. (seed == null) ? autoseed() : seed, 3), key);
  45. // Use the seed to initialize an ARC4 generator.
  46. var arc4 = new ARC4(key);
  47. // This function returns a random double in [0, 1) that contains
  48. // randomness in every bit of the mantissa of the IEEE 754 value.
  49. var prng = function() {
  50. var n = arc4.g(chunks), // Start with a numerator n < 2 ^ 48
  51. d = startdenom, // and denominator d = 2 ^ 48.
  52. x = 0; // and no 'extra last byte'.
  53. while (n < significance) { // Fill up all significant digits by
  54. n = (n + x) * width; // shifting numerator and
  55. d *= width; // denominator and generating a
  56. x = arc4.g(1); // new least-significant-byte.
  57. }
  58. while (n >= overflow) { // To avoid rounding up, before adding
  59. n /= 2; // last byte, shift everything
  60. d /= 2; // right using integer math until
  61. x >>>= 1; // we have exactly the desired bits.
  62. }
  63. return (n + x) / d; // Form the number within [0, 1).
  64. };
  65. prng.int32 = function() { return arc4.g(4) | 0; }
  66. prng.quick = function() { return arc4.g(4) / 0x100000000; }
  67. prng.double = prng;
  68. // Mix the randomness into accumulated entropy.
  69. mixkey(tostring(arc4.S), pool);
  70. // Calling convention: what to return as a function of prng, seed, is_math.
  71. return (options.pass || callback ||
  72. function(prng, seed, is_math_call, state) {
  73. if (state) {
  74. // Load the arc4 state from the given state if it has an S array.
  75. if (state.S) { copy(state, arc4); }
  76. // Only provide the .state method if requested via options.state.
  77. prng.state = function() { return copy(arc4, {}); }
  78. }
  79. // If called as a method of Math (Math.seedrandom()), mutate
  80. // Math.random because that is how seedrandom.js has worked since v1.0.
  81. if (is_math_call) { math[rngname] = prng; return seed; }
  82. // Otherwise, it is a newer calling convention, so return the
  83. // prng directly.
  84. else return prng;
  85. })(
  86. prng,
  87. shortseed,
  88. 'global' in options ? options.global : (this == math),
  89. options.state);
  90. }
  91. math['seed' + rngname] = seedrandom;
  92. //
  93. // ARC4
  94. //
  95. // An ARC4 implementation. The constructor takes a key in the form of
  96. // an array of at most (width) integers that should be 0 <= x < (width).
  97. //
  98. // The g(count) method returns a pseudorandom integer that concatenates
  99. // the next (count) outputs from ARC4. Its return value is a number x
  100. // that is in the range 0 <= x < (width ^ count).
  101. //
  102. function ARC4(key) {
  103. var t, keylen = key.length,
  104. me = this, i = 0, j = me.i = me.j = 0, s = me.S = [];
  105. // The empty key [] is treated as [0].
  106. if (!keylen) { key = [keylen++]; }
  107. // Set up S using the standard key scheduling algorithm.
  108. while (i < width) {
  109. s[i] = i++;
  110. }
  111. for (i = 0; i < width; i++) {
  112. s[i] = s[j = mask & (j + key[i % keylen] + (t = s[i]))];
  113. s[j] = t;
  114. }
  115. // The "g" method returns the next (count) outputs as one number.
  116. (me.g = function(count) {
  117. // Using instance members instead of closure state nearly doubles speed.
  118. var t, r = 0,
  119. i = me.i, j = me.j, s = me.S;
  120. while (count--) {
  121. t = s[i = mask & (i + 1)];
  122. r = r * width + s[mask & ((s[i] = s[j = mask & (j + t)]) + (s[j] = t))];
  123. }
  124. me.i = i; me.j = j;
  125. return r;
  126. // For robust unpredictability, the function call below automatically
  127. // discards an initial batch of values. This is called RC4-drop[256].
  128. // See http://google.com/search?q=rsa+fluhrer+response&btnI
  129. })(width);
  130. }
  131. //
  132. // copy()
  133. // Copies internal state of ARC4 to or from a plain object.
  134. //
  135. function copy(f, t) {
  136. t.i = f.i;
  137. t.j = f.j;
  138. t.S = f.S.slice();
  139. return t;
  140. };
  141. //
  142. // flatten()
  143. // Converts an object tree to nested arrays of strings.
  144. //
  145. function flatten(obj, depth) {
  146. var result = [], typ = (typeof obj), prop;
  147. if (depth && typ == 'object') {
  148. for (prop in obj) {
  149. try { result.push(flatten(obj[prop], depth - 1)); } catch (e) {}
  150. }
  151. }
  152. return (result.length ? result : typ == 'string' ? obj : obj + '\0');
  153. }
  154. //
  155. // mixkey()
  156. // Mixes a string seed into a key that is an array of integers, and
  157. // returns a shortened string seed that is equivalent to the result key.
  158. //
  159. function mixkey(seed, key) {
  160. var stringseed = seed + '', smear, j = 0;
  161. while (j < stringseed.length) {
  162. key[mask & j] =
  163. mask & ((smear ^= key[mask & j] * 19) + stringseed.charCodeAt(j++));
  164. }
  165. return tostring(key);
  166. }
  167. //
  168. // autoseed()
  169. // Returns an object for autoseeding, using window.crypto and Node crypto
  170. // module if available.
  171. //
  172. function autoseed() {
  173. try {
  174. var out;
  175. if (nodecrypto && (out = nodecrypto.randomBytes)) {
  176. // The use of 'out' to remember randomBytes makes tight minified code.
  177. out = out(width);
  178. } else {
  179. out = new Uint8Array(width);
  180. (global.crypto || global.msCrypto).getRandomValues(out);
  181. }
  182. return tostring(out);
  183. } catch (e) {
  184. var browser = global.navigator,
  185. plugins = browser && browser.plugins;
  186. return [+new Date, global, plugins, global.screen, tostring(pool)];
  187. }
  188. }
  189. //
  190. // tostring()
  191. // Converts an array of charcodes to a string
  192. //
  193. function tostring(a) {
  194. return String.fromCharCode.apply(0, a);
  195. }
  196. //
  197. // When seedrandom.js is loaded, we immediately mix a few bits
  198. // from the built-in RNG into the entropy pool. Because we do
  199. // not want to interfere with deterministic PRNG state later,
  200. // seedrandom will not call math.random on its own again after
  201. // initialization.
  202. //
  203. mixkey(math.random(), pool);
  204. //
  205. // Nodejs and AMD support: export the implementation as a module using
  206. // either convention.
  207. //
  208. if ((typeof module) == 'object' && module.exports) {
  209. module.exports = seedrandom;
  210. // When in node.js, try using crypto package for autoseeding.
  211. try {
  212. nodecrypto = require('crypto');
  213. } catch (ex) {}
  214. } else if ((typeof define) == 'function' && define.amd) {
  215. define(function() { return seedrandom; });
  216. }
  217. // End anonymous scope, and pass initial values.
  218. })(
  219. [], // pool: entropy pool starts empty
  220. Math // math: package containing random, pow, and seedrandom
  221. );