diff --git a/lib/rng-browser.js b/lib/rng-browser.js index ac39b128..ab843826 100644 --- a/lib/rng-browser.js +++ b/lib/rng-browser.js @@ -2,25 +2,23 @@ // browser this is a little complicated due to unknown quality of Math.random() // and inconsistent support for the `crypto` API. We do the best we can via // feature-detection -var rng; -var crypto = global.crypto || global.msCrypto; // for IE 11 -if (crypto && crypto.getRandomValues) { +if (typeof(crypto) != 'undefined' && crypto.getRandomValues) { // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef - rng = function whatwgRNG() { + + module.exports = function whatwgRNG() { crypto.getRandomValues(rnds8); return rnds8; }; -} - -if (!rng) { +} else { // Math.random()-based (RNG) // // If all else fails, use Math.random(). It's fast, but is of unspecified // quality. var rnds = new Array(16); - rng = function() { + + module.exports = function mathRNG() { for (var i = 0, r; i < 16; i++) { if ((i & 0x03) === 0) r = Math.random() * 0x100000000; rnds[i] = r >>> ((i & 0x03) << 3) & 0xff; @@ -29,5 +27,3 @@ if (!rng) { return rnds; }; } - -module.exports = rng; diff --git a/lib/rng.js b/lib/rng.js index 4a0182fd..58f0dc9c 100644 --- a/lib/rng.js +++ b/lib/rng.js @@ -1,10 +1,8 @@ // Unique ID creation requires a high quality random # generator. In node.js // this is pretty straight-forward - we use the crypto API. -var rb = require('crypto').randomBytes; +var crypto = require('crypto'); -function rng() { - return rb(16); -} - -module.exports = rng; +module.exports = function nodeRNG() { + return crypto.randomBytes(16); +}; diff --git a/test/test.js b/test/test.js index c35a1eea..f7734c55 100644 --- a/test/test.js +++ b/test/test.js @@ -46,6 +46,41 @@ function compare(name, ids) { }); } +test('nodeRNG', function() { + var rng = require('../lib/rng'); + + var bytes = rng(); +console.log(rng.toString()); + assert.equal(bytes.length, 16); + bytes.forEach(function(v) {return typeof(v) == 'number'}); +}); + +test('browser mathRNG', function() { + var rng = require('../lib/rng-browser'); + + assert.equal(rng.name, 'mathRNG'); + + var bytes = rng(); + assert.equal(bytes.length, 16); + bytes.forEach(function(v) {return typeof(v) == 'number'}); +}); + +test('browser cryptoRNG', function() { + global.crypto = { + getRandomValues: function(arr) { + return randomFillSync(arr); + } + }; + + var rng = require('../lib/rng-browser'); + + delete global.crypto; + + var bytes = rng(); + assert.equal(bytes.length, 16); + bytes.forEach(function(v) {return typeof(v) == 'number'}); +}); + test('sha1 node', function() { var sha1 = require('../lib/sha1');