Skip to content

Commit

Permalink
Do not simply try catch, cheack availabilty instead.
Browse files Browse the repository at this point in the history
  • Loading branch information
evanvosberg committed Feb 11, 2020
1 parent 0241952 commit 20b827d
Showing 1 changed file with 34 additions and 9 deletions.
43 changes: 34 additions & 9 deletions src/core.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,22 +11,47 @@ var CryptoJS = CryptoJS || (function (Math, undefined) {
* As Math.random() is cryptographically not safe to use
*/
var cryptoSecureRandomInt = function () {
// Native crypto module on NodeJS environment
try {
// Native crypto from global object or import via require
var crypto = global.crypto || require('crypto');
var crypto;

return crypto.randomBytes(4).readInt32LE();
// Native crypto module in Browser environment
try {
if (typeof window !== 'undefined') {
if (window.crypto) {
// Support experimental crypto module in IE 11
crypto = window.crypto;
} else if (window.msCrypto) {
// Support experimental crypto module in IE 11
crypto = window.msCrypto;
}
}
} catch (err) {}

// Native crypto module in Browser environment
// Native crypto module on NodeJS environment
try {
// Support experimental crypto module in IE 11
var crypto = window.crypto || window.msCrypto;
if (typeof global !== 'undefined' && global.crypto) {
// Native crypto from global
crypto = global.crypto;
} else if (typeof require === 'function') {
// Native crypto import via require
crypto = require('crypto');
}

return crypto.getRandomValues(new Uint32Array(1))[0];
} catch (err) {}

// Use getRandomValues method
if (crypto && typeof crypto.getRandomValues === 'function') {
try {
return crypto.getRandomValues(new Uint32Array(1))[0];
} catch (err) {}
}

// Use randomBytes method
if (crypto && typeof crypto.randomBytes === 'function') {
try {
return crypto.randomBytes(4).readInt32LE();
} catch (err) {}
}

throw new Error('Native crypto module could not be used to get secure random number.');
};

Expand Down

0 comments on commit 20b827d

Please sign in to comment.