Skip to content

Commit

Permalink
fix(random-bytes): wrap crypto require in try/catch for fallback
Browse files Browse the repository at this point in the history
  • Loading branch information
mbroadst committed Oct 23, 2018
1 parent 5b9ce62 commit 47fd5f7
Showing 1 changed file with 14 additions and 12 deletions.
26 changes: 14 additions & 12 deletions lib/parser/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,21 @@ function normalizedFunctionString(fn) {
return fn.toString().replace('function(', 'function (');
}

let randomBytes;
if (typeof window !== 'undefined') {
if (window.crypto && window.crypto.getRandomValues) {
randomBytes = size => window.crypto.getRandomValues(new Uint8Array(size));
} else {
randomBytes = size => {
const result = new Uint8Array(size);
for (let i = 0; i < size; ++i) result[i] = Math.floor(Math.random() * 256);
return result;
};
}
function insecureRandomBytes(size) {
const result = new Uint8Array(size);
for (let i = 0; i < size; ++i) result[i] = Math.floor(Math.random() * 256);
return result;
}

let randomBytes = insecureRandomBytes;
if (typeof window !== 'undefined' && window.crypto && window.crypto.getRandomValues) {
randomBytes = size => window.crypto.getRandomValues(new Uint8Array(size));
} else {
randomBytes = require('crypto').randomBytes;
try {
randomBytes = require('crypto').randomBytes;
} catch (e) {
// keep the fallback
}
}

module.exports = {
Expand Down

0 comments on commit 47fd5f7

Please sign in to comment.