base64.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. 'use strict';
  2. // private property
  3. var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4. // public method for encoding
  5. exports.encode = function(input, utf8) {
  6. var output = "";
  7. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8. var i = 0;
  9. while (i < input.length) {
  10. chr1 = input.charCodeAt(i++);
  11. chr2 = input.charCodeAt(i++);
  12. chr3 = input.charCodeAt(i++);
  13. enc1 = chr1 >> 2;
  14. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  15. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  16. enc4 = chr3 & 63;
  17. if (isNaN(chr2)) {
  18. enc3 = enc4 = 64;
  19. }
  20. else if (isNaN(chr3)) {
  21. enc4 = 64;
  22. }
  23. output = output + _keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
  24. }
  25. return output;
  26. };
  27. // public method for decoding
  28. exports.decode = function(input, utf8) {
  29. var output = "";
  30. var chr1, chr2, chr3;
  31. var enc1, enc2, enc3, enc4;
  32. var i = 0;
  33. input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
  34. while (i < input.length) {
  35. enc1 = _keyStr.indexOf(input.charAt(i++));
  36. enc2 = _keyStr.indexOf(input.charAt(i++));
  37. enc3 = _keyStr.indexOf(input.charAt(i++));
  38. enc4 = _keyStr.indexOf(input.charAt(i++));
  39. chr1 = (enc1 << 2) | (enc2 >> 4);
  40. chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
  41. chr3 = ((enc3 & 3) << 6) | enc4;
  42. output = output + String.fromCharCode(chr1);
  43. if (enc3 != 64) {
  44. output = output + String.fromCharCode(chr2);
  45. }
  46. if (enc4 != 64) {
  47. output = output + String.fromCharCode(chr3);
  48. }
  49. }
  50. return output;
  51. };