rng-browser.js 1.1 KB

123456789101112131415161718192021222324252627282930313233
  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. // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation.
  6. var getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues.bind(crypto)) ||
  7. (typeof(msCrypto) != 'undefined' && msCrypto.getRandomValues.bind(msCrypto));
  8. if (getRandomValues) {
  9. // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto
  10. var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef
  11. module.exports = function whatwgRNG() {
  12. getRandomValues(rnds8);
  13. return rnds8;
  14. };
  15. } else {
  16. // Math.random()-based (RNG)
  17. //
  18. // If all else fails, use Math.random(). It's fast, but is of unspecified
  19. // quality.
  20. var rnds = new Array(16);
  21. module.exports = function mathRNG() {
  22. for (var i = 0, r; i < 16; i++) {
  23. if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
  24. rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
  25. }
  26. return rnds;
  27. };
  28. }