urlsafe-base64.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*!
  2. * urlsafe-base64
  3. */
  4. /**
  5. * Module Dependencies
  6. */
  7. // None yet!
  8. /**
  9. * Library version.
  10. */
  11. exports.version = '1.0.0';
  12. /**
  13. * .encode
  14. *
  15. * return an encoded Buffer as URL Safe Base64
  16. *
  17. * Note: This function encodes to the RFC 4648 Spec where '+' is encoded
  18. * as '-' and '/' is encoded as '_'. The padding character '=' is
  19. * removed.
  20. *
  21. * @param {Buffer} buffer
  22. * @return {String}
  23. * @api public
  24. */
  25. exports.encode = function encode(buffer) {
  26. return buffer.toString('base64')
  27. .replace(/\+/g, '-') // Convert '+' to '-'
  28. .replace(/\//g, '_') // Convert '/' to '_'
  29. .replace(/=+$/, ''); // Remove ending '='
  30. };
  31. /**
  32. * .decode
  33. *
  34. * return an decoded URL Safe Base64 as Buffer
  35. *
  36. * @param {String}
  37. * @return {Buffer}
  38. * @api public
  39. */
  40. exports.decode = function decode(base64) {
  41. // Add removed at end '='
  42. base64 += Array(5 - base64.length % 4).join('=');
  43. base64 = base64
  44. .replace(/\-/g, '+') // Convert '-' to '+'
  45. .replace(/\_/g, '/'); // Convert '_' to '/'
  46. return new Buffer(base64, 'base64');
  47. };
  48. /**
  49. * .validate
  50. *
  51. * Validates a string if it is URL Safe Base64 encoded.
  52. *
  53. * @param {String}
  54. * @return {Boolean}
  55. * @api public
  56. */
  57. exports.validate = function validate(base64) {
  58. return /^[A-Za-z0-9\-_]+$/.test(base64);
  59. };