Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to base64 encode inside of javascript

I am trying to implement a simple script on a site that will return base64 encoded information from google's ajax API. This is what I am playing with so far:

<html>
<head>
<script src="http://www.google.com/jsapi?key=ABQIAAAA0duujonFsEX871htGWZBHRS76H0qhS7Lb-D1Gd0Mnaiuid8Z7BQIyz2kMpojKizoyiCQA4yRkKAKug" type="text/javascript"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
  jQuery(document).ready(function() {
    var location = 'Unable to determine your location.';
    if (google.loader.ClientLocation) {
      var loc = google.loader.ClientLocation;
      location = 'Country: <strong>' + loc.address.country + '</strong>, Region: <strong>' + loc.address.region + '</strong>, City: <strong>' +
                 loc.address.city + '</strong>, Lat/Long: <strong>' + loc.latitude + ', ' + loc.longitude + '</strong>';
    }
    jQuery('.geolocation').html(location);
  });
</script>
</head>
<body>
<span class="geolocation"></span>
</body>
</html>

It returns the info I am trying to get properly, but I need to base64 encode the separate parts such as country, region, city, lat and longitude. In php it would be simple, but I cannot figure out how to do it in javascript. Any help would be appreciated.

like image 755
Mike Avatar asked Sep 23 '10 00:09

Mike


People also ask

How do you do Base64 encode in JS?

In JavaScript there are two functions respectively for decoding and encoding Base64 strings: btoa() : creates a Base64-encoded ASCII string from a "string" of binary data ("btoa" should be read as "binary to ASCII"). atob() : decodes a Base64-encoded string("atob" should be read as "ASCII to binary").

What is Base64 in JavaScript?

Encoding and Decoding Strings with Base64 btoa() and atob() are two Base64 helper functions that are a core part of the HTML specification and available in all modern browsers. Note: The naming of these functions reference old Unix commands for converting binary to ASCII (btoa) and ASCII to binary (atob).


2 Answers

Mozilla, WebKit and Opera all have btoa() and atob() functions for base 64 encoding and decoding respectively. Use those where possible because they will almost certainly be massively faster than a JavaScript implementation and fall back to one of the many scripts that turn up when you do a web search.

EDIT 10 SEPTEMBER 2013: atob() and btoa() do not handle Unicode characters outside the ASCII range. MDN has workarounds but I can't vouch for them. Thanks to @larspars for pointing this out.

For example, if you were using the example from amphetamachine's answer, you could do the following:

if (!window.btoa) {     window.btoa = function(str) {         return Base64.encode(str);     } }  if (!window.atob) {     window.atob = function(str) {         return Base64.decode(str);     } }  alert( btoa("Some text") ); 
like image 135
Tim Down Avatar answered Sep 28 '22 04:09

Tim Down


This answer seems to match what you're looking for.

There's also this one which is more elegant:

/**
 *
 *  Base64 encode / decode
 *  http://www.webtoolkit.info/
 *
 **/

var Base64 = {

    // private property
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

    // public method for encoding
    encode : function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = Base64._utf8_encode(input);

        while (i < input.length) {

            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output = output +
            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

        }

        return output;
    },

    // public method for decoding
    decode : function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {

            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }

        }

        output = Base64._utf8_decode(output);

        return output;

    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}
like image 33
amphetamachine Avatar answered Sep 28 '22 03:09

amphetamachine