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.
24 lines
673 B
JavaScript
24 lines
673 B
JavaScript
var imports = require('soop');
|
|
|
|
var SecureRandom = require('../common/SecureRandom');
|
|
|
|
SecureRandom.getRandomBuffer = function(size) {
|
|
if (!window.crypto && !window.msCrypto)
|
|
throw new Error('window.crypto not available');
|
|
|
|
if (window.crypto && window.crypto.getRandomValues)
|
|
var crypto = window.crypto;
|
|
else if (window.msCrypto && window.msCrypto.getRandomValues) //internet explorer
|
|
var crypto = window.msCrypto;
|
|
else
|
|
throw new Error('window.crypto.getRandomValues not available');
|
|
|
|
var bbuf = new Uint8Array(size);
|
|
crypto.getRandomValues(bbuf);
|
|
var buf = new Buffer(bbuf);
|
|
|
|
return buf;
|
|
};
|
|
|
|
module.exports = require('soop')(SecureRandom);
|