diff --git a/lib/rng-browser.js b/lib/rng-browser.js index 6361fb81..dead6ada 100644 --- a/lib/rng-browser.js +++ b/lib/rng-browser.js @@ -23,12 +23,16 @@ if (getRandomValues) { // quality. var rnds = new Array(16); - module.exports = function mathRNG() { + 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; } return rnds; - }; + } + mathRNG.insecure = true; + mathRNG.insecureMessage = 'No CSPRNG provided. Provide a cryptographically secure rng' + + ' via `rng` option or set `allowInsecureRNG` to true'; + module.exports = mathRNG; } diff --git a/test/test.js b/test/test.js index d15df3e7..1a48881b 100644 --- a/test/test.js +++ b/test/test.js @@ -64,6 +64,8 @@ test('mathRNG', function() { var rng = require('../lib/rng-browser'); assert.equal(rng.name, 'mathRNG'); + assert.equal(rng.insecure, true) + var bytes = rng(); assert.equal(bytes.length, 16); diff --git a/v1.js b/v1.js index d84c0f45..745a33f7 100644 --- a/v1.js +++ b/v1.js @@ -22,6 +22,9 @@ function v1(options, buf, offset) { var node = options.node || _nodeId; var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; + if (rng.insecure && !options.allowInsecureRNG) + throw new Error(rng.insecureMessage); + // node and clockseq need to be initialized to random values if they're not // specified. We do this lazily to minimize issues related to insufficient // system entropy. See #189 diff --git a/v4.js b/v4.js index 1f07be1c..893a2f0e 100644 --- a/v4.js +++ b/v4.js @@ -12,6 +12,9 @@ function v4(options, buf, offset) { var rnds = options.random || (options.rng || rng)(); + if (rng.insecure && !options.allowInsecureRNG) + throw new Error(rng.insecureMessage); + // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` rnds[6] = (rnds[6] & 0x0f) | 0x40; rnds[8] = (rnds[8] & 0x3f) | 0x80;