Base64.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. //https://github.com/davidchambers/Base64.js
  2. ;(function () {
  3. var object = typeof exports != 'undefined' ? exports : this; // #8: web workers
  4. var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  5. function InvalidCharacterError(message) {
  6. this.message = message;
  7. }
  8. InvalidCharacterError.prototype = new Error;
  9. InvalidCharacterError.prototype.name = 'InvalidCharacterError';
  10. // encoder
  11. // [https://gist.github.com/999166] by [https://github.com/nignag]
  12. object.btoa || (
  13. object.btoa = function (input) {
  14. for (
  15. // initialize result and counter
  16. var block, charCode, idx = 0, map = chars, output = '';
  17. // if the next input index does not exist:
  18. // change the mapping table to "="
  19. // check if d has no fractional digits
  20. input.charAt(idx | 0) || (map = '=', idx % 1);
  21. // "8 - idx % 1 * 8" generates the sequence 2, 4, 6, 8
  22. output += map.charAt(63 & block >> 8 - idx % 1 * 8)
  23. ) {
  24. charCode = input.charCodeAt(idx += 3/4);
  25. if (charCode > 0xFF) {
  26. throw new InvalidCharacterError("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");
  27. }
  28. block = block << 8 | charCode;
  29. }
  30. return output;
  31. });
  32. // decoder
  33. // [https://gist.github.com/1020396] by [https://github.com/atk]
  34. object.atob || (
  35. object.atob = function (input) {
  36. input = input.replace(/=+$/, '')
  37. if (input.length % 4 == 1) {
  38. throw new InvalidCharacterError("'atob' failed: The string to be decoded is not correctly encoded.");
  39. }
  40. for (
  41. // initialize result and counters
  42. var bc = 0, bs, buffer, idx = 0, output = '';
  43. // get next character
  44. buffer = input.charAt(idx++);
  45. // character found in table? initialize bit storage and add its ascii value;
  46. ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
  47. // and if not first of each 4 characters,
  48. // convert the first 8 bits to one ascii character
  49. bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0
  50. ) {
  51. // try to find character in table (0-63, not found => -1)
  52. buffer = chars.indexOf(buffer);
  53. }
  54. return output;
  55. });
  56. }());