From 20b827da1b70e68180e3fc055a0e1ee43b06843a Mon Sep 17 00:00:00 2001 From: evanvosberg Date: Tue, 11 Feb 2020 16:13:21 +0100 Subject: [PATCH] Do not simply try catch, cheack availabilty instead. --- src/core.js | 43 ++++++++++++++++++++++++++++++++++--------- 1 file changed, 34 insertions(+), 9 deletions(-) diff --git a/src/core.js b/src/core.js index c97925b..6bfec9b 100644 --- a/src/core.js +++ b/src/core.js @@ -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.'); };