@@ -11,22 +11,47 @@ var CryptoJS = CryptoJS || (function (Math, undefined) {
11
11
* As Math.random() is cryptographically not safe to use
12
12
*/
13
13
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 ;
18
15
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
+ }
20
27
} catch ( err ) { }
21
28
22
- // Native crypto module in Browser environment
29
+ // Native crypto module on NodeJS environment
23
30
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
+ }
26
38
27
- return crypto . getRandomValues ( new Uint32Array ( 1 ) ) [ 0 ] ;
28
39
} catch ( err ) { }
29
40
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
+
30
55
throw new Error ( 'Native crypto module could not be used to get secure random number.' ) ;
31
56
} ;
32
57
0 commit comments