Skip to content

Commit 20b827d

Browse files
committed
Do not simply try catch, cheack availabilty instead.
1 parent 0241952 commit 20b827d

File tree

1 file changed

+34
-9
lines changed

1 file changed

+34
-9
lines changed

src/core.js

Lines changed: 34 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,22 +11,47 @@ var CryptoJS = CryptoJS || (function (Math, undefined) {
1111
* As Math.random() is cryptographically not safe to use
1212
*/
1313
var cryptoSecureRandomInt = function () {
14-
// Native crypto module on NodeJS environment
15-
try {
16-
// Native crypto from global object or import via require
17-
var crypto = global.crypto || require('crypto');
14+
var crypto;
1815

19-
return crypto.randomBytes(4).readInt32LE();
16+
// Native crypto module in Browser environment
17+
try {
18+
if (typeof window !== 'undefined') {
19+
if (window.crypto) {
20+
// Support experimental crypto module in IE 11
21+
crypto = window.crypto;
22+
} else if (window.msCrypto) {
23+
// Support experimental crypto module in IE 11
24+
crypto = window.msCrypto;
25+
}
26+
}
2027
} catch (err) {}
2128

22-
// Native crypto module in Browser environment
29+
// Native crypto module on NodeJS environment
2330
try {
24-
// Support experimental crypto module in IE 11
25-
var crypto = window.crypto || window.msCrypto;
31+
if (typeof global !== 'undefined' && global.crypto) {
32+
// Native crypto from global
33+
crypto = global.crypto;
34+
} else if (typeof require === 'function') {
35+
// Native crypto import via require
36+
crypto = require('crypto');
37+
}
2638

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

41+
// Use getRandomValues method
42+
if (crypto && typeof crypto.getRandomValues === 'function') {
43+
try {
44+
return crypto.getRandomValues(new Uint32Array(1))[0];
45+
} catch (err) {}
46+
}
47+
48+
// Use randomBytes method
49+
if (crypto && typeof crypto.randomBytes === 'function') {
50+
try {
51+
return crypto.randomBytes(4).readInt32LE();
52+
} catch (err) {}
53+
}
54+
3055
throw new Error('Native crypto module could not be used to get secure random number.');
3156
};
3257

0 commit comments

Comments
 (0)