base64.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. define("dojox/encoding/base64", ["dojo/_base/lang"], function(lang) {
  2. var base64 = lang.getObject("dojox.encoding.base64", true);
  3. /*=====
  4. base64 = dojox.encoding.base64;
  5. =====*/
  6. var p="=";
  7. var tab="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  8. base64.encode=function(/* byte[] */ba){
  9. // summary
  10. // Encode an array of bytes as a base64-encoded string
  11. var s=[], l=ba.length;
  12. var rm=l%3;
  13. var x=l-rm;
  14. for (var i=0; i<x;){
  15. var t=ba[i++]<<16|ba[i++]<<8|ba[i++];
  16. s.push(tab.charAt((t>>>18)&0x3f));
  17. s.push(tab.charAt((t>>>12)&0x3f));
  18. s.push(tab.charAt((t>>>6)&0x3f));
  19. s.push(tab.charAt(t&0x3f));
  20. }
  21. // deal with trailers, based on patch from Peter Wood.
  22. switch(rm){
  23. case 2:{
  24. var t=ba[i++]<<16|ba[i++]<<8;
  25. s.push(tab.charAt((t>>>18)&0x3f));
  26. s.push(tab.charAt((t>>>12)&0x3f));
  27. s.push(tab.charAt((t>>>6)&0x3f));
  28. s.push(p);
  29. break;
  30. }
  31. case 1:{
  32. var t=ba[i++]<<16;
  33. s.push(tab.charAt((t>>>18)&0x3f));
  34. s.push(tab.charAt((t>>>12)&0x3f));
  35. s.push(p);
  36. s.push(p);
  37. break;
  38. }
  39. }
  40. return s.join(""); // string
  41. };
  42. base64.decode=function(/* string */str){
  43. // summary
  44. // Convert a base64-encoded string to an array of bytes
  45. var s=str.split(""), out=[];
  46. var l=s.length;
  47. while(s[--l]==p){ } // strip off trailing padding
  48. for (var i=0; i<l;){
  49. var t=tab.indexOf(s[i++])<<18;
  50. if(i<=l){ t|=tab.indexOf(s[i++])<<12 };
  51. if(i<=l){ t|=tab.indexOf(s[i++])<<6 };
  52. if(i<=l){ t|=tab.indexOf(s[i++]) };
  53. out.push((t>>>16)&0xff);
  54. out.push((t>>>8)&0xff);
  55. out.push(t&0xff);
  56. }
  57. // strip off any null bytes
  58. while(out[out.length-1]==0){ out.pop(); }
  59. return out; // byte[]
  60. };
  61. return base64;
  62. });