base64.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. Copyright (c) 2004-2012, The Dojo Foundation All Rights Reserved.
  3. Available via Academic Free License >= 2.1 OR the modified BSD license.
  4. see: http://dojotoolkit.org/license for details
  5. */
  6. if(!dojo._hasResource["dojox.encoding.base64"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
  7. dojo._hasResource["dojox.encoding.base64"] = true;
  8. dojo.provide("dojox.encoding.base64");
  9. dojo.getObject("encoding.base64", true, dojox);
  10. (function(){
  11. var p="=";
  12. var tab="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  13. var dxe=dojox.encoding;
  14. dxe.base64.encode=function(/* byte[] */ba){
  15. // summary
  16. // Encode an array of bytes as a base64-encoded string
  17. var s=[], l=ba.length;
  18. var rm=l%3;
  19. var x=l-rm;
  20. for (var i=0; i<x;){
  21. var t=ba[i++]<<16|ba[i++]<<8|ba[i++];
  22. s.push(tab.charAt((t>>>18)&0x3f));
  23. s.push(tab.charAt((t>>>12)&0x3f));
  24. s.push(tab.charAt((t>>>6)&0x3f));
  25. s.push(tab.charAt(t&0x3f));
  26. }
  27. // deal with trailers, based on patch from Peter Wood.
  28. switch(rm){
  29. case 2:{
  30. var t=ba[i++]<<16|ba[i++]<<8;
  31. s.push(tab.charAt((t>>>18)&0x3f));
  32. s.push(tab.charAt((t>>>12)&0x3f));
  33. s.push(tab.charAt((t>>>6)&0x3f));
  34. s.push(p);
  35. break;
  36. }
  37. case 1:{
  38. var t=ba[i++]<<16;
  39. s.push(tab.charAt((t>>>18)&0x3f));
  40. s.push(tab.charAt((t>>>12)&0x3f));
  41. s.push(p);
  42. s.push(p);
  43. break;
  44. }
  45. }
  46. return s.join(""); // string
  47. };
  48. dxe.base64.decode=function(/* string */str){
  49. // summary
  50. // Convert a base64-encoded string to an array of bytes
  51. var s=str.split(""), out=[];
  52. var l=s.length;
  53. while(s[--l]==p){ } // strip off trailing padding
  54. for (var i=0; i<l;){
  55. var t=tab.indexOf(s[i++])<<18;
  56. if(i<=l){ t|=tab.indexOf(s[i++])<<12 };
  57. if(i<=l){ t|=tab.indexOf(s[i++])<<6 };
  58. if(i<=l){ t|=tab.indexOf(s[i++]) };
  59. out.push((t>>>16)&0xff);
  60. out.push((t>>>8)&0xff);
  61. out.push(t&0xff);
  62. }
  63. // strip off any null bytes
  64. while(out[out.length-1]==0){ out.pop(); }
  65. return out; // byte[]
  66. };
  67. })();
  68. }