0

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)?

TheBigC
  • 605
  • 3
  • 9
  • 17

1 Answers1

1

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.

alex
  • 11,935
  • 3
  • 30
  • 42
  • Base64 is not url safe, http://stackoverflow.com/questions/8855687/secure-random-token-in-node-js, so it wouldn't be ideal for my problem unless I used technique from this question – TheBigC Feb 27 '14 at 00:16
  • Just do a `.replace()` after, no big deal. My point is: an amount of characters is important, but it is not the only thing that matters. AFAIR, `Math.random()` uses Mersenne-Twister algorithm with 32 bit seed which is hard, but possible to predict. – alex Feb 27 '14 at 00:34