2016-02-06 19:32:42 +00:00
|
|
|
var randomId;
|
|
|
|
|
|
|
|
if ((typeof window !== 'undefined') &&
|
|
|
|
(typeof window.crypto !== 'undefined') &&
|
|
|
|
(typeof window.crypto.getRandomValues !== 'undefined')) {
|
2016-05-12 01:03:11 +00:00
|
|
|
randomId = function (byteCount, hexOutput) {
|
2016-02-06 19:32:42 +00:00
|
|
|
var buf = new Uint8Array(byteCount);
|
|
|
|
window.crypto.getRandomValues(buf);
|
2016-05-12 01:03:11 +00:00
|
|
|
if (hexOutput) {
|
|
|
|
var encoded = [];
|
|
|
|
for (var i = 0; i < buf.length; i++) {
|
|
|
|
encoded.push("0123456789abcdef"[(buf[i] >> 4) & 15]);
|
|
|
|
encoded.push("0123456789abcdef"[buf[i] & 15]);
|
|
|
|
}
|
|
|
|
return encoded.join('');
|
|
|
|
} else {
|
|
|
|
return btoa(String.fromCharCode.apply(null, buf)).replace(/=/g,'');
|
|
|
|
}
|
2016-02-06 19:32:42 +00:00
|
|
|
};
|
|
|
|
} else {
|
2016-03-18 21:01:00 +00:00
|
|
|
var crypto;
|
|
|
|
try {
|
|
|
|
crypto = require('crypto');
|
|
|
|
} catch (e) {}
|
|
|
|
if ((typeof crypto !== 'undefined') &&
|
|
|
|
(typeof crypto.randomBytes !== 'undefined')) {
|
2016-05-12 01:03:11 +00:00
|
|
|
randomId = function (byteCount, hexOutput) {
|
|
|
|
if (hexOutput) {
|
|
|
|
return crypto.randomBytes(byteCount).hexSlice().replace(/=/g,'');
|
|
|
|
} else {
|
|
|
|
return crypto.randomBytes(byteCount).base64Slice().replace(/=/g,'');
|
|
|
|
}
|
2016-03-18 21:01:00 +00:00
|
|
|
};
|
|
|
|
} else {
|
|
|
|
console.warn('No suitable implementation for RandomID.randomId available.');
|
|
|
|
}
|
2016-02-06 19:32:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
module.exports.randomId = randomId;
|