Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
177
rated 0 times [  182] [ 5]  / answers: 1 / hits: 42948  / 11 Years ago, fri, november 29, 2013, 12:00:00

I need a random sequence of bytes for making a password hash. In Ruby, this would look like:



 File.open(/dev/urandom).read(20).each_byte{|x| rand << sprintf(%02x,x)}


In Node.js, I can get a sequence of random bytes with:



 var randomSource = RandBytes.urandom.getInstance();
var bytes = randomSource.getRandomBytesAsync(20);


But the problem is, how to convert these to a String?



Also, I need to have them wrapped in promisses. Would this work:



   get_rand()
.then(function(bytes) {
authToken = bytes;
})

More From » node.js

 Answers
4

randbytes works asynchronously. If you want to combine it with promises, you need to use a Promises-lib as well. I'm using when as an example:



var when          = require('when');
var RandBytes = require('randbytes');
var randomSource = RandBytes.urandom.getInstance();

function get_rand() {
var dfd = when.defer();
randomSource.getRandomBytes(20, function(bytes) {
dfd.resolve( bytes.toString('hex') ); // convert to hex string
});
return dfd.promise;
}

// example call:
get_rand().then(function(bytes) {
console.log('random byte string:', bytes);
});

[#73999] Wednesday, November 27, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
luna

Total Points: 698
Total Questions: 114
Total Answers: 93

Location: Israel
Member since Wed, Apr 14, 2021
3 Years ago
;