Last active
December 15, 2015 22:19
-
-
Save zivester/5332362 to your computer and use it in GitHub Desktop.
encoding/decoding and Buffers
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
| // Return a buffer, that when encoded to base64, will be of size "length" | |
| exports.randomBytesBase64 = function(length){ | |
| length = Math.ceil(length * 3/4); | |
| return require('crypto').randomBytes(length); | |
| } | |
| // Take a buffer and create a base64, url safe encoding | |
| exports.urlEncode = function(buffer){ | |
| return buffer.toString('base64').replace(/\//g,'_').replace(/\+/g,'-'); | |
| } | |
| exports.urlDecode = function(string){ | |
| return new Buffer(string.replace(/_/g,'/').replace(/\-/g,'+'), 'base64'); | |
| } | |
| var original = exports.randomBytesBase64(8), | |
| encoded = exports.urlEncode(original), | |
| decoded = exports.urlDecode(encoded); | |
| // original should be the same as decoded | |
| console.log(original, encoded.toString(), decoded, original.toString() == decoded.toString()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment