Skip to content

Commit b405ff5

Browse files
committed
Add secure random using native crypto module.
1 parent 8e6d15b commit b405ff5

File tree

1 file changed

+31
-21
lines changed

1 file changed

+31
-21
lines changed

src/core.js

Lines changed: 31 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,34 @@
22
* CryptoJS core components.
33
*/
44
var CryptoJS = CryptoJS || (function (Math, undefined) {
5+
6+
/*
7+
* Cryptographically secure pseudorandom number generator
8+
*
9+
* As Math.random() is cryptographically not safe to use
10+
*/
11+
var secureRandom = function () {
12+
// Native crypto module on NodeJS environment
13+
try {
14+
// Crypto from global object
15+
var crypto = global.crypto;
16+
17+
// Create a random float number between 0 and 1
18+
return Number('0.' + crypto.randomBytes(3).readUIntBE(0, 3));
19+
} catch (err) {}
20+
21+
// Native crypto module in Browser environment
22+
try {
23+
// Support experimental crypto module in IE 11
24+
var crypto = window.crypto || window.msCrypto;
25+
26+
// Create a random float number between 0 and 1
27+
return Number('0.' + window.crypto.getRandomValues(new Uint32Array(1))[0]);
28+
} catch (err) {}
29+
30+
throw new Error('Native crypto module could not be used to get secure random number.');
31+
};
32+
533
/*
634
* Local polyfil of Object.create
735
*/
@@ -289,26 +317,8 @@ var CryptoJS = CryptoJS || (function (Math, undefined) {
289317
random: function (nBytes) {
290318
var words = [];
291319

292-
var r = function (m_w) {
293-
var m_w = m_w;
294-
var m_z = 0x3ade68b1;
295-
var mask = 0xffffffff;
296-
297-
return function () {
298-
m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask;
299-
m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask;
300-
var result = ((m_z << 0x10) + m_w) & mask;
301-
result /= 0x100000000;
302-
result += 0.5;
303-
return result * (Math.random() > 0.5 ? 1 : -1);
304-
}
305-
};
306-
307-
for (var i = 0, rcache; i < nBytes; i += 4) {
308-
var _r = r((rcache || Math.random()) * 0x100000000);
309-
310-
rcache = _r() * 0x3ade67b7;
311-
words.push((_r() * 0x100000000) | 0);
320+
for (var i = 0; i < nBytes; i += 4) {
321+
words.push((secureRandom() * 0x100000000) | 0);
312322
}
313323

314324
return new WordArray.init(words, nBytes);
@@ -540,7 +550,7 @@ var CryptoJS = CryptoJS || (function (Math, undefined) {
540550
*/
541551
_process: function (doFlush) {
542552
var processedWords;
543-
553+
544554
// Shortcuts
545555
var data = this._data;
546556
var dataWords = data.words;

0 commit comments

Comments
 (0)