Secure random token in Node.js

Javascriptnode.jsBase64Securestring

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

Synchronous option in-case if you are not a JS expert like me. Had to spend some time on how to access the inline function variable

var token = crypto.randomBytes(64).toString('hex');

Solution 3 - Javascript

1. Using nanoid third party library [NEW!]


> A tiny, secure, URL-friendly, unique string ID generator for JavaScript

https://github.com/ai/nanoid

import { nanoid } from "nanoid";
const id = nanoid(48);


2. Base 64 Encoding with URL and Filename Safe Alphabet


Page 7 of RCF 4648 describes how to encode in base 64 with URL safety. You can use an existing library like base64url to do the job.

The function will be:

var crypto = require('crypto');
var base64url = require('base64url');

/** Sync */
function randomStringAsBase64Url(size) {
  return base64url(crypto.randomBytes(size));
}

Usage example:

randomStringAsBase64Url(20);
// Returns 'AXSGpLVjne_f7w5Xg-fWdoBwbfs' which is 27 characters length.

Note that the returned string length will not match with the size argument (size != final length).


3. Crypto random values from limited set of characters


> Beware that with this solution the generated random string is not uniformly distributed.

You can also build a strong random string from a limited set of characters like that:

var crypto = require('crypto');

/** Sync */
function randomString(length, chars) {
  if (!chars) {
    throw new Error('Argument \'chars\' is undefined');
  }

  const charsLength = chars.length;
  if (charsLength > 256) {
    throw new Error('Argument \'chars\' should not have more than 256 characters'
      + ', otherwise unpredictability will be broken');
  }

  const randomBytes = crypto.randomBytes(length);
  let result = new Array(length);

  let cursor = 0;
  for (let i = 0; i < length; i++) {
    cursor += randomBytes[i];
    result[i] = chars[cursor % charsLength];
  }

  return result.join('');
}

/** Sync */
function randomAsciiString(length) {
  return randomString(length,
    'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789');
}

Usage example:

randomAsciiString(20);
// Returns 'rmRptK5niTSey7NlDk5y' which is 20 characters length.

randomString(20, 'ABCDEFG');
// Returns 'CCBAAGDGBBEGBDBECDCE' which is 20 characters length.

Solution 4 - Javascript

The up-to-date right way to do this asynchronously using ES 2016 standards of async and await (as of Node 7) would be the following:

const crypto = require('crypto');

function generateToken({ stringBase = 'base64', byteLength = 48 } = {}) {
  return new Promise((resolve, reject) => {
    crypto.randomBytes(byteLength, (err, buffer) => {
      if (err) {
        reject(err);
      } else {
        resolve(buffer.toString(stringBase));
      }
    });
  });
}

async function handler(req, res) {
   // default token length
   const newToken = await generateToken();
   console.log('newToken', newToken);

   // pass in parameters - adjust byte length
   const shortToken = await generateToken({byteLength: 20});
   console.log('newToken', shortToken);
}

This works out of the box in Node 7 without any Babel transformations

Solution 5 - Javascript

Random URL and filename string safe (1 liner)

Crypto.randomBytes(48).toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/\=/g, '');

Solution 6 - Javascript

With async/await and promisification.

const crypto = require('crypto')
const randomBytes = Util.promisify(crypto.randomBytes)
const plain = (await randomBytes(24)).toString('base64').replace(/\W/g, '')

Generates something similar to VjocVHdFiz5vGHnlnwqJKN0NdeHcz8eM

Solution 7 - Javascript

Check out:

var crypto = require('crypto');
crypto.randomBytes(Math.ceil(length/2)).toString('hex').slice(0,length);

Solution 8 - Javascript

As of Node.js 14.18 and 15.7, url-safe base64 encoding support is built-in:

const token = crypto.randomBytes(48).toString('base64url');

If you want to use the async version (because the function may have to wait for entropy), it can be promisified to align better with modern patterns:

const randomBytesAsync = util.promisify(crypto.randomBytes);

const token = (await randomBytesAsync(48)).toString('base64url');

Solution 9 - Javascript

Look at real_ates ES2016 way, it's more correct. ECMAScript 2016 (ES7) way

import crypto from 'crypto';

function spawnTokenBuf() {
    return function(callback) {
        crypto.randomBytes(48, callback);
    };
}

async function() {
    console.log((await spawnTokenBuf()).toString('base64'));
};

Generator/Yield Way

var crypto = require('crypto');
var co = require('co');

function spawnTokenBuf() {
    return function(callback) {
        crypto.randomBytes(48, callback);
    };
}

co(function* () {
    console.log((yield spawnTokenBuf()).toString('base64'));
});

Solution 10 - Javascript

crypto-random-string is a nice module for this.

const cryptoRandomString = require('crypto-random-string');
 
cryptoRandomString({length: 10});                          // => '2cf05d94db'
cryptoRandomString({length: 10, type: 'base64'});          // => 'YMiMbaQl6I'
cryptoRandomString({length: 10, type: 'url-safe'});        // => 'YN-tqc8pOw'
cryptoRandomString({length: 10, type: 'numeric'});         // => '8314659141'
cryptoRandomString({length: 6, type: 'distinguishable'});  // => 'CDEHKM'
cryptoRandomString({length: 10, type: 'ascii-printable'}); // => '`#Rt8$IK>B'
cryptoRandomString({length: 10, type: 'alphanumeric'});    // => 'DMuKL8YtE7'
cryptoRandomString({length: 10, characters: 'abc'});       // => 'abaaccabac'

cryptoRandomString.async(options) add .async if you want to get a promise.

Solution 11 - Javascript

https://www.npmjs.com/package/crypto-extra has a method for it :)

var value = crypto.random(/* desired length */)

Solution 12 - Javascript

The npm module anyid provides flexible API to generate various kinds of string ID / code.

To generate random string in A-Za-z0-9 using 48 random bytes:

const id = anyid().encode('Aa0').bits(48 * 8).random().id();
// G4NtiI9OYbSgVl3EAkkoxHKyxBAWzcTI7aH13yIUNggIaNqPQoSS7SpcalIqX0qGZ

To generate fixed length alphabet only string filled by random bytes:

const id = anyid().encode('Aa').length(20).random().id();
// qgQBBtDwGMuFHXeoVLpt

Internally it uses crypto.randomBytes() to generate random.

Solution 13 - Javascript

Simple function that gets you a token that is URL safe and has base64 encoding! It's a combination of 2 answers from above.

const randomToken = () => {
    crypto.randomBytes(64).toString('base64').replace(/\//g,'_').replace(/\+/g,'-');
}

Solution 14 - Javascript

You can use the random-token lib. it's very easy to use . :)

var randomToken = require('random-token').create('abcdefghijklmnopqrstuvwxzyABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789');
var token = randomToken(16);

And also you can not use different salt

var randomToken = require('random-token');
var token = randomToken(16); // output -> d8d4kd29c40f021 ```

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHubert OGView Question on Stackoverflow
Solution 1 - JavascriptthejhView Answer on Stackoverflow
Solution 2 - Javascriptphoenix2010View Answer on Stackoverflow
Solution 3 - JavascriptYves M.View Answer on Stackoverflow
Solution 4 - Javascriptreal_ateView Answer on Stackoverflow
Solution 5 - JavascriptKedemView Answer on Stackoverflow
Solution 6 - JavascriptZnarkusView Answer on Stackoverflow
Solution 7 - JavascriptsudamView Answer on Stackoverflow
Solution 8 - JavascriptInklingView Answer on Stackoverflow
Solution 9 - JavascriptbasickarlView Answer on Stackoverflow
Solution 10 - JavascriptHasan Sefa OzalpView Answer on Stackoverflow
Solution 11 - JavascriptjsonmaurView Answer on Stackoverflow
Solution 12 - JavascriptaleungView Answer on Stackoverflow
Solution 13 - JavascriptdctsView Answer on Stackoverflow
Solution 14 - JavascriptxManView Answer on Stackoverflow