base64.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // This code was written by Tyler Akins and has been placed in the
  2. // public domain. It would be nice if you left this header intact.
  3. // Base64 code from Tyler Akins -- http://rumkin.com
  4. var Base64 = (function () {
  5. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  6. var obj = {
  7. /**
  8. * Encodes a string in base64
  9. * @param {String} input The string to encode in base64.
  10. */
  11. encode: function (input) {
  12. var output = "";
  13. var chr1, chr2, chr3;
  14. var enc1, enc2, enc3, enc4;
  15. var i = 0;
  16. do {
  17. chr1 = input.charCodeAt(i++);
  18. chr2 = input.charCodeAt(i++);
  19. chr3 = input.charCodeAt(i++);
  20. enc1 = chr1 >> 2;
  21. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  22. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  23. enc4 = chr3 & 63;
  24. if (isNaN(chr2)) {
  25. enc3 = enc4 = 64;
  26. } else if (isNaN(chr3)) {
  27. enc4 = 64;
  28. }
  29. output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  30. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  31. } while (i < input.length);
  32. return output;
  33. },
  34. /**
  35. * Decodes a base64 string.
  36. * @param {String} input The string to decode.
  37. */
  38. decode: function (input) {
  39. var output = "";
  40. var chr1, chr2, chr3;
  41. var enc1, enc2, enc3, enc4;
  42. var i = 0;
  43. // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
  44. input = input.replace(/[^A-Za-z0-9\+\/\=]/g, '');
  45. do {
  46. enc1 = keyStr.indexOf(input.charAt(i++));
  47. enc2 = keyStr.indexOf(input.charAt(i++));
  48. enc3 = keyStr.indexOf(input.charAt(i++));
  49. enc4 = keyStr.indexOf(input.charAt(i++));
  50. chr1 = (enc1 << 2) | (enc2 >> 4);
  51. chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
  52. chr3 = ((enc3 & 3) << 6) | enc4;
  53. output = output + String.fromCharCode(chr1);
  54. if (enc3 != 64) {
  55. output = output + String.fromCharCode(chr2);
  56. }
  57. if (enc4 != 64) {
  58. output = output + String.fromCharCode(chr3);
  59. }
  60. } while (i < input.length);
  61. return output;
  62. }
  63. };
  64. return obj;
  65. })();
  66. // Nodify
  67. exports.Base64 = Base64;