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.
29 lines
636 B
JavaScript
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);
|