base64.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. export function encode(input) {
  2. let _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  3. let chr1, chr2, chr3, enc1, enc2, enc3, enc4, i = 0,
  4. output = '',
  5. utftext = '';
  6. input = input.replace(/\r\n/g, "\n");
  7. for (let n = 0; n < input.length; n++) {
  8. let c = input.charCodeAt(n);
  9. if (c < 128) {
  10. utftext += String.fromCharCode(c);
  11. } else if ((c > 127) && (c < 2048)) {
  12. utftext += String.fromCharCode((c >> 6) | 192);
  13. utftext += String.fromCharCode((c & 63) | 128);
  14. } else {
  15. utftext += String.fromCharCode((c >> 12) | 224);
  16. utftext += String.fromCharCode(((c >> 6) & 63) | 128);
  17. utftext += String.fromCharCode((c & 63) | 128);
  18. }
  19. }
  20. while (i < utftext.length) {
  21. chr1 = utftext.charCodeAt(i++);
  22. chr2 = utftext.charCodeAt(i++);
  23. chr3 = utftext.charCodeAt(i++);
  24. enc1 = chr1 >> 2;
  25. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  26. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  27. enc4 = chr3 & 63;
  28. if (isNaN(chr2)) {
  29. enc3 = enc4 = 64;
  30. } else if (isNaN(chr3)) {
  31. enc4 = 64;
  32. }
  33. output = output +
  34. _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
  35. _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
  36. }
  37. return output;
  38. }