Skip to content

Instantly share code, notes, and snippets.

@OllieJones
Created October 3, 2017 12:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OllieJones/37b63ac3452fdb24a13c12c139f81715 to your computer and use it in GitHub Desktop.
Save OllieJones/37b63ac3452fdb24a13c12c139f81715 to your computer and use it in GitHub Desktop.
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