So, uuid4 just uses crypto.randomBytes()
itself:
function uuid4() {
var rnd = crypto.randomBytes(16);
rnd[6] = (rnd[6] & 0x0f) | 0x40;
rnd[8] = (rnd[8] & 0x3f) | 0x80;
rnd = rnd.toString("hex").match(/(.{8})(.{4})(.{4})(.{4})(.{12})/);
rnd.shift();
return rnd.join("-");
}
But, it's only generating an initial 16 byte long value and it's then modifying that. If you really want to know the performance of the two, as with all performance related questions, you will have to benchmark each and compare, but if you make them the same length, then it's unlikely you find a big difference.
Either should work fine. Both are going to put a small tax on the event loop because of the use of the synchronous version of crypto.randomBytes()
, but in proper use with the session this should only get triggered when a user first arrives on your site without an existing session cookie so it is not a recurring tax on every request.
Either should be plenty secure from a session guessability point of view. When it comes to security, I tend to go with widely used and widely scrutinized libraries instead of rolling my own solution since I figure that people who know far more than I do about security have been looking at the widely used solution.
Here's a descriptive post about uuid4()
with some commentary about the extremely low possibility of a collision. It also explains what the bit twiddling you see in the uuid4()
code is there for.