base.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. export function weBtoa(string){
  2. var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
  3. b64re = /^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/;
  4. string = String(string);
  5. var bitmap, a, b, c,
  6. result = "",
  7. i = 0,
  8. rest = string.length % 3; // To determine the final padding
  9. for (; i < string.length;) {
  10. if ((a = string.charCodeAt(i++)) > 255 ||
  11. (b = string.charCodeAt(i++)) > 255 ||
  12. (c = string.charCodeAt(i++)) > 255)
  13. throw new TypeError("Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.");
  14. bitmap = (a << 16) | (b << 8) | c;
  15. result += b64.charAt(bitmap >> 18 & 63) + b64.charAt(bitmap >> 12 & 63) +
  16. b64.charAt(bitmap >> 6 & 63) + b64.charAt(bitmap & 63);
  17. }
  18. // If there's need of padding, replace the last 'A's with equal signs
  19. return rest ? result.slice(0, rest - 3) + "===".substring(rest) : result;
  20. }
  21. export function weAtob(string){
  22. // atob can work with strings with whitespaces, even inside the encoded part,
  23. // but only \t, \n, \f, \r and ' ', which can be stripped.
  24. var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
  25. b64re = /^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/;
  26. string = String(string).replace(/[\t\n\f\r ]+/g, "");
  27. if (!b64re.test(string))
  28. throw new TypeError("Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.");
  29. // Adding the padding if missing, for semplicity
  30. string += "==".slice(2 - (string.length & 3));
  31. var bitmap, result = "",
  32. r1, r2, i = 0;
  33. for (; i < string.length;) {
  34. bitmap = b64.indexOf(string.charAt(i++)) << 18 | b64.indexOf(string.charAt(i++)) << 12 |
  35. (r1 = b64.indexOf(string.charAt(i++))) << 6 | (r2 = b64.indexOf(string.charAt(i++)));
  36. result += r1 === 64 ? String.fromCharCode(bitmap >> 16 & 255) :
  37. r2 === 64 ? String.fromCharCode(bitmap >> 16 & 255, bitmap >> 8 & 255) :
  38. String.fromCharCode(bitmap >> 16 & 255, bitmap >> 8 & 255, bitmap & 255);
  39. }
  40. return result;
  41. }