twitst4tz

twitter statistics web application
Log | Files | Refs | README | LICENSE

rng-browser.js (1312B)


      1 // Unique ID creation requires a high quality random # generator.  In the
      2 // browser this is a little complicated due to unknown quality of Math.random()
      3 // and inconsistent support for the `crypto` API.  We do the best we can via
      4 // feature-detection
      5 
      6 // getRandomValues needs to be invoked in a context where "this" is a Crypto
      7 // implementation. Also, find the complete implementation of crypto on IE11.
      8 var getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto)) ||
      9                       (typeof(msCrypto) != 'undefined' && typeof window.msCrypto.getRandomValues == 'function' && msCrypto.getRandomValues.bind(msCrypto));
     10 
     11 if (getRandomValues) {
     12   // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto
     13   var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef
     14 
     15   module.exports = function whatwgRNG() {
     16     getRandomValues(rnds8);
     17     return rnds8;
     18   };
     19 } else {
     20   // Math.random()-based (RNG)
     21   //
     22   // If all else fails, use Math.random().  It's fast, but is of unspecified
     23   // quality.
     24   var rnds = new Array(16);
     25 
     26   module.exports = function mathRNG() {
     27     for (var i = 0, r; i < 16; i++) {
     28       if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
     29       rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
     30     }
     31 
     32     return rnds;
     33   };
     34 }