2016-07-27 09:53:40 +03:00
|
|
|
'use strict';
|
|
|
|
|
2017-02-24 22:41:24 +03:00
|
|
|
var defineProperty = require('./properties.js').defineProperty;
|
2016-07-27 09:53:40 +03:00
|
|
|
|
|
|
|
var crypto = global.crypto || global.msCrypto;
|
|
|
|
if (!crypto || !crypto.getRandomValues) {
|
|
|
|
console.log('WARNING: Missing strong random number source; using weak randomBytes');
|
|
|
|
crypto = {
|
2017-03-08 09:51:04 +03:00
|
|
|
getRandomValues: function(buffer) {
|
|
|
|
for (var round = 0; round < 20; round++) {
|
|
|
|
for (var i = 0; i < buffer.length; i++) {
|
|
|
|
if (round) {
|
|
|
|
buffer[i] ^= parseInt(256 * Math.random());
|
|
|
|
} else {
|
|
|
|
buffer[i] = parseInt(256 * Math.random());
|
|
|
|
}
|
|
|
|
}
|
2016-07-27 09:53:40 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
return buffer;
|
|
|
|
},
|
|
|
|
_weakCrypto: true
|
|
|
|
};
|
|
|
|
} else {
|
|
|
|
console.log('Found strong random number source');
|
|
|
|
}
|
|
|
|
|
|
|
|
function randomBytes(length) {
|
|
|
|
if (length <= 0 || length > 1024 || parseInt(length) != length) {
|
|
|
|
throw new Error('invalid length');
|
|
|
|
}
|
|
|
|
|
2017-02-24 22:41:24 +03:00
|
|
|
var result = new Uint8Array(length);
|
|
|
|
crypto.getRandomValues(result);
|
|
|
|
return result;
|
2016-07-27 09:53:40 +03:00
|
|
|
};
|
|
|
|
|
|
|
|
if (crypto._weakCrypto === true) {
|
2017-04-06 20:39:21 +03:00
|
|
|
defineProperty(randomBytes, '_weakCrypto', true);
|
2016-07-27 09:53:40 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = randomBytes;
|