made proper synchronous random bytes generator
This commit is contained in:
parent
d7dbe078dc
commit
af43a539b6
41
index.js
41
index.js
|
@ -2,22 +2,37 @@ if (typeof Buffer === 'undefined') {
|
|||
global.Buffer = require('buffer').Buffer
|
||||
}
|
||||
|
||||
var deasync = require('deasync');
|
||||
var sjcl = require('sjcl');
|
||||
var sjclRandom = new sjcl.prng(10);
|
||||
|
||||
var {
|
||||
RNRandomBytes
|
||||
} = require('react-native').NativeModules;
|
||||
var RNRandomBytes = require('react-native').NativeModules.RNRandomBytes;
|
||||
|
||||
module.exports.randomBytes = function(length, cb) {
|
||||
|
||||
export default function randomBytes(length, cb) {
|
||||
if (!cb) {
|
||||
// throw new Error('synchronous API not supported')
|
||||
var exec = deasync(RNRandomBytes.randomBytes);
|
||||
var base64String = exec(length);
|
||||
return new Buffer(base64String, 'base64');
|
||||
var size = length;
|
||||
var wordCount = Math.ceil(size * 0.25);
|
||||
sjclRandom.isReady(3);
|
||||
var randomBytes = sjclRandom.randomWords(wordCount);
|
||||
var hexString = sjcl.codec.hex.fromBits(randomBytes);
|
||||
hexString = hexString.substr(0, size * 2);
|
||||
|
||||
return new Buffer(hexString, 'hex');
|
||||
}
|
||||
|
||||
RNRandomBytes.randomBytes(length, function(err, base64String) {
|
||||
if (err) cb(err)
|
||||
else cb(null, new Buffer(base64String, 'base64'))
|
||||
})
|
||||
}
|
||||
if (err) {
|
||||
cb(err)
|
||||
}
|
||||
|
||||
else {
|
||||
cb(null, new Buffer(base64String, 'base64'))
|
||||
}
|
||||
});
|
||||
|
||||
};
|
||||
|
||||
module.exports.randomBytes(4096, function(err, base64String){
|
||||
var hexString = base64String.toString('hex');
|
||||
sjclRandom.addEntropy(hexString);
|
||||
});
|
||||
|
|
|
@ -15,7 +15,7 @@
|
|||
],
|
||||
"dependencies": {
|
||||
"buffer": "^3.5.2",
|
||||
"deasync": "^0.1.4"
|
||||
"sjcl": "^1.0.3"
|
||||
},
|
||||
"author": "Mark Vayngrib <mark.vayngrib@lablz.com> (http://github.com/mvayngrib)",
|
||||
"license": "ISC"
|
||||
|
|
Loading…
Reference in New Issue