Reputation: 605
Is there any particular reason why I should choose either of these techniques for generating a random string in nodejs?
First:
//var TOKEN_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var TOKEN_CHARS = 'abcdef0123456789';
var len = 24;
var chars = [];
for (var i = 0; i < len; i++) {
var index = Math.floor(Math.random() * TOKEN_CHARS.length);
chars.push(TOKEN_CHARS[index]);
}
console.log(chars.join(''));
Second:
var token = require('crypto').randomBytes(len/2).toString('hex');
console.log(token);
At first glance the output of these look similar. I don't understand fully, but as far as I can tell from researching Math.random() may not be the best technique based on the fact the "seed" has to do with the system time and is not truly random. However the highly used connect library uses the first technique so I assume it must be pretty good.
If I were to use the first technique, would the token be "more" secure using the commented out TOKEN_CHARS (simply due to more possibilities for each character)?
Upvotes: 0
Views: 910
Reputation: 12265
Math.random()
is created as a general purpose PRNG, crypto.pseudoRandomBytes
is a part of OpenSSL library and is created as a CSPRNG. So it's a good reason to use second one.
If I were to use the first technique, would the token be "more" secure using the commented out TOKEN_CHARS
No. However, if you want more entropy in your token, you can use .toString('base64')
in the second case, this way it'll use 64 characters to represent your token.
Upvotes: 1