flocore/lib/common/SecureRandom.js
Ryan X. Charles ba692aaa20 add new SecureRandom class that does the right thing
Generating random numbers properly depends on the platform. The new
getRandomBuffer method does the right thing on the right platform. It will
sometimes fail due to insufficient entropy. The getPseudoRandomBuffer class is
also provided that will never fail, but it is not cryptographically secure and
should not be used for keys.
2014-04-22 22:18:59 -03:00

29 lines
636 B
JavaScript

var imports = require('soop');
var SecureRandom = function() {
};
/* secure random bytes that sometimes throws an error due to lack of entropy */
SecureRandom.getRandomBuffer = function() {};
/* insecure random bytes, but it never fails */
SecureRandom.getPseudoRandomBuffer = function(size) {
var b32 = 0x100000000;
var b = new Buffer(size);
for (var i = 0; i <= size; i++) {
var j = Math.floor(i / 4);
var k = i - j * 4;
if (k == 0) {
r = Math.random() * b32;
b[i] = r & 0xff;
} else {
b[i] = (r = r >>> 8) & 0xff;
}
}
return b;
};
module.exports = require('soop')(SecureRandom);