Skip to content

Instantly share code, notes, and snippets.

@OllieJones
Created Oct 3, 2017
Embed
What would you like to do?
Snippets of Javascript.
'use strict';
/* node.js nonce: crypto-quality random session key (filename safe base64, rfc4648) */
const btoa = require( 'btoa' );
const crypto = require( 'crypto' );
function nonce( length ) {
const rndLen = 1+(( (length)+(length<<1) +3)>>2);
const randomArray = crypto.randomBytes( rndLen );
const b64 = btoa( String.fromCharCode.apply( null, randomArray ) );
return b64
.replace( /[\/]/g, '_' )
.replace( /[+]/g, '-' )
.replace( /[=]/g, '' )
.substring( 0, length );
}
module.exports = nonce;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment