Created
October 3, 2017 12:28
-
-
Save OllieJones/37b63ac3452fdb24a13c12c139f81715 to your computer and use it in GitHub Desktop.
Snippets of Javascript.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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