[php] seedrandom em php

Viewer

copydownloadembedprintName: seedrandom em php
  1. <?php 
  2. $var = '// seedrandom.js
  3. // Author: David Bau 3/11/2010
  4. // http://davidbau.com/archives/2010/01/30/random_seeds_coded_hints_and_quintillions.html
  5. // http://davidbau.com/encode/seedrandom.js
  6. //
  7. // Defines a method Math.seedrandom() that, when called, substitutes
  8. // an explicitly seeded RC4-based algorithm for Math.random().  Also
  9. // supports automatic seeding from local or network sources of entropy.
  10. //
  11. // Usage:
  12. //
  13. //   <script src=http://davidbau.com/encode/seedrandom-min.js></script>
  14. //
  15. //   Math.seedrandom(\'yipee\'); Sets Math.random to a function that is
  16. //                             initialized using the given explicit seed.
  17. //
  18. //   Math.seedrandom();        Sets Math.random to a function that is
  19. //                             seeded using the current time, dom state,
  20. //                             and other accumulated local entropy.
  21. //                             The generated seed string is returned.
  22. //
  23. //   Math.seedrandom(\'yowza\', true);
  24. //                             Seeds using the given explicit seed mixed
  25. //                             together with accumulated entropy.
  26. //
  27. //   <script src="http://bit.ly/srandom-512"></script>
  28. //                             Seeds using physical random bits downloaded
  29. //                             from random.org.
  30. //
  31. // Examples:
  32. //
  33. //   Math.seedrandom("hello");            // Use "hello" as the seed.
  34. //   document.write(Math.random());       // Always 0.5463663768140734
  35. //   document.write(Math.random());       // Always 0.43973793770592234
  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.
  40. //
  41. //   Math.random = rng1;                  // Continue "hello" prng sequence.
  42. //   document.write(Math.random());       // Always 0.554769432473455
  43. //
  44. //   Math.seedrandom(autoseed);           // Restart at the previous seed.
  45. //   document.write(Math.random());       // Repeat the \'unpredictable\' value.
  46. //
  47. // Notes:
  48. //
  49. // Each time seedrandom(\'arg\') is called, entropy from the passed seed
  50. // is accumulated in a pool to help generate future seeds for the
  51. // zero-argument form of Math.seedrandom, so entropy can be injected over
  52. // time by calling seedrandom with explicit data repeatedly.
  53. //
  54. // On speed - This javascript implementation of Math.random() is about
  55. // 3-10x slower than the built-in Math.random() because it is not native
  56. // code, but this is typically fast enough anyway.  Seeding is more expensive,
  57. // especially if you use auto-seeding.  Some details (timings on Chrome 4):
  58. //
  59. // Our Math.random()            - avg less than 0.002 milliseconds per call
  60. // seedrandom(\'explicit\')       - avg less than 0.5 milliseconds per call
  61. // seedrandom(\'explicit\', true) - avg less than 2 milliseconds per call
  62. // seedrandom()                 - avg about 38 milliseconds per call
  63. //
  64. // LICENSE (BSD):
  65. //
  66. // Copyright 2010 David Bau, all rights reserved.
  67. //
  68. // Redistribution and use in source and binary forms, with or without
  69. // modification, are permitted provided that the following conditions are met:
  70. // 
  71. //   1. Redistributions of source code must retain the above copyright
  72. //      notice, this list of conditions and the following disclaimer.
  73. //
  74. //   2. Redistributions in binary form must reproduce the above copyright
  75. //      notice, this list of conditions and the following disclaimer in the
  76. //      documentation and/or other materials provided with the distribution.
  77. // 
  78. //   3. Neither the name of this module nor the names of its contributors may
  79. //      be used to endorse or promote products derived from this software
  80. //      without specific prior written permission.
  81. // 
  82. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  83. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  84. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  85. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  86. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  87. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  88. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  89. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  90. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  91. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  92. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  93. //
  94. /**
  95.  * All code is in an anonymous closure to keep the global namespace clean.
  96.  *
  97.  * @param {number=} overflow 
  98.  * @param {number=} startdenom
  99.  */
  100. (function (pool, math, width, chunks, significance, overflow, startdenom) {
  101.  
  102.  
  103. //
  104. // seedrandom()
  105. // This is the seedrandom function described above.
  106. //
  107. math[\'seedrandom\'] = function seedrandom(seed, use_entropy) {
  108.   var key = [];
  109.   var arc4;
  110.  
  111.   // Flatten the seed string or build one from local entropy if needed.
  112.   seed = mixkey(flatten(
  113.     use_entropy ? [seed, pool] :
  114.     arguments.length ? seed :
  115.     [new Date().getTime(), pool, window], 3), key);
  116.  
  117.   // Use the seed to initialize an ARC4 generator.
  118.   arc4 = new ARC4(key);
  119.  
  120.   // Mix the randomness into accumulated entropy.
  121.   mixkey(arc4.S, pool);
  122.  
  123.   // Override Math.random
  124.  
  125.   // This function returns a random double in [0, 1) that contains
  126.   // randomness in every bit of the mantissa of the IEEE 754 value.
  127.  
  128.   math[\'random\'] = function random() {  // Closure to return a random double:
  129.     var n = arc4.g(chunks);             // Start with a numerator n < 2 ^ 48
  130.     var d = startdenom;                 //   and denominator d = 2 ^ 48.
  131.     var x = 0;                          //   and no \'extra last byte\'.
  132.     while (n < significance) {          // Fill up all significant digits by
  133.       n = (n + x) * width;              //   shifting numerator and
  134.       d *= width;                       //   denominator and generating a
  135.       x = arc4.g(1);                    //   new least-significant-byte.
  136.     }
  137.     while (n >= overflow) {             // To avoid rounding up, before adding
  138.       n /= 2;                           //   last byte, shift everything
  139.       d /= 2;                           //   right using integer math until
  140.       x >>>= 1;                         //   we have exactly the desired bits.
  141.     }
  142.     return (n + x) / d;                 // Form the number within [0, 1).
  143.   };
  144.  
  145.   // Return the seed that was used
  146.   return seed;
  147. };
  148.  
  149. //
  150. // ARC4
  151. //
  152. // An ARC4 implementation.  The constructor takes a key in the form of
  153. // an array of at most (width) integers that should be 0 <= x < (width).
  154. //
  155. // The g(count) method returns a pseudorandom integer that concatenates
  156. // the next (count) outputs from ARC4.  Its return value is a number x
  157. // that is in the range 0 <= x < (width ^ count).
  158. //
  159. /** @constructor */
  160. function ARC4(key) {
  161.   var t, u, me = this, keylen = key.length;
  162.   var i = 0, j = me.i = me.j = me.m = 0;
  163.   me.S = [];
  164.   me.c = [];
  165.  
  166.   // The empty key [] is treated as [0].
  167.   if (!keylen) { key = [keylen++]; }
  168.  
  169.   // Set up S using the standard key scheduling algorithm.
  170.   while (i < width) { me.S[i] = i++; }
  171.   for (i = 0; i < width; i++) {
  172.     t = me.S[i];
  173.     j = lowbits(j + t + key[i % keylen]);
  174.     u = me.S[j];
  175.     me.S[i] = u;
  176.     me.S[j] = t;
  177.   }
  178.  
  179.   // The "g" method returns the next (count) outputs as one number.
  180.   me.g = function getnext(count) {
  181.     var s = me.S;
  182.     var i = lowbits(me.i + 1); var t = s[i];
  183.     var j = lowbits(me.j + t); var u = s[j];
  184.     s[i] = u;
  185.     s[j] = t;
  186.     var r = s[lowbits(t + u)];
  187.     while (--count) {
  188.       i = lowbits(i + 1); t = s[i];
  189.       j = lowbits(j + t); u = s[j];
  190.       s[i] = u;
  191.       s[j] = t;
  192.       r = r * width + s[lowbits(t + u)];
  193.     }
  194.     me.i = i;
  195.     me.j = j;
  196.     return r;
  197.   };
  198.   // For robust unpredictability discard an initial batch of values.
  199.   // See http://www.rsa.com/rsalabs/node.asp?id=2009
  200.   me.g(width);
  201. }
  202.  
  203. //
  204. // flatten()
  205. // Converts an object tree to nested arrays of strings.
  206. //
  207. /** @param {Object=} result 
  208.   * @param {string=} prop */
  209. function flatten(obj, depth, result, prop) {
  210.   result = [];
  211.   if (depth && typeof(obj) == \'object\') {
  212.     for (prop in obj) {
  213.       if (prop.indexOf(\'S\') < 5) {    // Avoid FF3 bug (local/sessionStorage)
  214.         try { result.push(flatten(obj[prop], depth - 1)); } catch (e) {}
  215.       }
  216.     }
  217.   }
  218.   return result.length ? result : \'\' + obj;
  219. }
  220.  
  221. //
  222. // mixkey()
  223. // Mixes a string seed into a key that is an array of integers, and
  224. // returns a shortened string seed that is equivalent to the result key.
  225. //
  226. /** @param {number=} smear 
  227.   * @param {number=} j */
  228. function mixkey(seed, key, smear, j) {
  229.   seed += \'\';                         // Ensure the seed is a string
  230.   smear = 0;
  231.   for (j = 0; j < seed.length; j++) {
  232.     key[lowbits(j)] =
  233.       lowbits((smear ^= key[lowbits(j)] * 19) + seed.charCodeAt(j));
  234.   }
  235.   seed = \'\';
  236.   for (j in key) { seed += String.fromCharCode(key[j]); }
  237.   return seed;
  238. }
  239.  
  240. //
  241. // lowbits()
  242. // A quick "n mod width" for width a power of 2.
  243. //
  244. function lowbits(n) { return n & (width - 1); }
  245.  
  246. //
  247. // The following constants are related to IEEE 754 limits.
  248. //
  249. startdenom = math.pow(width, chunks);
  250. significance = math.pow(2, significance);
  251. overflow = significance * 2;
  252.  
  253. //
  254. // When seedrandom.js is loaded, we immediately mix a few bits
  255. // from the built-in RNG into the entropy pool.  Because we do
  256. // not want to intefere with determinstic PRNG state later,
  257. // seedrandom will not call math.random on its own again after
  258. // initialization.
  259. //
  260. mixkey(math.random(), pool);
  261.  
  262. // End anonymous scope, and pass initial values.
  263. })(
  264.   [],   // pool: entropy pool starts empty
  265.   Math, // math: package containing random, pow, and seedrandom
  266.   256,  // width: each RC4 output is 0 <= x < 256
  267.   6,    // chunks: at least six RC4 outputs for each double
  268.   52    // significance: there are 52 significant digits in a double
  269. );
  270. ';

Editor

You can edit this paste and save as new:


File Description
  • seedrandom em php
  • Paste Code
  • 25 Apr-2024
  • 9.99 Kb
You can Share it: