Posted By

icoder on 09/07/09


Tagged

base64


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

vali29
cu39
wirenaught


Base64


 / Published in: JavaScript
 

Take 1

  1. var Base64 = function() {
  2. var _key = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3. var _keyRe = new RegExp("[^" + _key + "=]", "g");
  4. return {
  5. encode: function(input) {
  6. var output = "";
  7. var len = input.length, i = 0, padding = 3 - (len % 3);
  8. while (i < len) {
  9. var byte1 = input.charCodeAt(i++);
  10. var byte2 = input.charCodeAt(i++) || 0;
  11. var byte3 = input.charCodeAt(i++) || 0;
  12. var index1 = byte1 >> 2;
  13. var index2 = (byte1 & 3) << 4 | byte2 >> 4;
  14. var index3 = (byte2 & 15) << 2 | byte3 >> 6;
  15. var index4 = byte3 & 63;
  16. output += _key.charAt(index1) + _key.charAt(index2) + _key.charAt(index3) + _key.charAt(index4);
  17. }
  18. if (padding)
  19. output = output.slice(0, output.length - padding) + (padding == 1 ? "=" : "==");
  20. return output;
  21. },
  22. decode: function(input) {
  23. input = input.replace(_keyRe, "");
  24. var output = "";
  25. var i = 0, len = input.length, padding = len - input.indexOf("=");
  26. while (i < len) {
  27. var byte1 = _key.indexOf(input.substr(i++, 1));
  28. var byte2 = _key.indexOf(input.substr(i++, 1));
  29. var byte3 = _key.indexOf(input.substr(i++, 1));
  30. var byte4 = _key.indexOf(input.substr(i++, 1));
  31. var char1 = byte1 << 2 | byte2 >> 4;
  32. var char2 = ((byte2 & 15) << 4) | (byte3 >> 2);
  33. var char3 = ((byte3 & 3) << 6) | byte4 & 63;
  34. output += String.fromCharCode(char1) + String.fromCharCode(char2) + String.fromCharCode(char3);
  35. }
  36. if (padding)
  37. output = output.substr(0, output.length - padding);
  38. return output;
  39. }
  40. };
  41. } ();

Report this snippet  

You need to login to post a comment.