rng.js (719B)
1 // Original code adapted from Robert Kieffer. 2 // details at https://github.com/broofa/node-uuid 3 (function() { 4 var _global = this; 5 6 var mathRNG, whatwgRNG; 7 8 // NOTE: Math.random() does not guarantee "cryptographic quality" 9 mathRNG = function(size) { 10 var bytes = new Array(size); 11 var r; 12 13 for (var i = 0, r; i < size; i++) { 14 if ((i & 0x03) == 0) r = Math.random() * 0x100000000; 15 bytes[i] = r >>> ((i & 0x03) << 3) & 0xff; 16 } 17 18 return bytes; 19 } 20 21 if (_global.crypto && crypto.getRandomValues) { 22 whatwgRNG = function(size) { 23 var bytes = new Uint8Array(size); 24 crypto.getRandomValues(bytes); 25 return bytes; 26 } 27 } 28 29 module.exports = whatwgRNG || mathRNG; 30 31 }())