Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Secure random token in Node.js

In this question Erik needs to generate a secure random token in Node.js. There's the method crypto.randomBytes that generates a random Buffer. However, the base64 encoding in node is not url-safe, it includes / and + instead of - and _. Therefore, the easiest way to generate such token I've found is

require('crypto').randomBytes(48, function(ex, buf) {     token = buf.toString('base64').replace(/\//g,'_').replace(/\+/g,'-'); }); 

Is there a more elegant way?

like image 868
Hubert OG Avatar asked Jan 13 '12 18:01

Hubert OG


1 Answers

Try crypto.randomBytes():

require('crypto').randomBytes(48, function(err, buffer) {   var token = buffer.toString('hex'); }); 

The 'hex' encoding works in node v0.6.x or newer.

like image 55
thejh Avatar answered Sep 22 '22 10:09

thejh