简体   繁体   English

如何在javascript里面进行base64编码

[英]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. 我试图在网站上实现一个简单的脚本,该脚本将从google的ajax API返回base64编码信息。 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. 它返回我正在尝试正确的信息,但我需要base64编码单独的部分,如国家,地区,城市,纬度和经度。 In php it would be simple, but I cannot figure out how to do it in javascript. 在PHP中它会很简单,但我无法弄清楚如何在javascript中做到这一点。 Any help would be appreciated. 任何帮助,将不胜感激。

Mozilla, WebKit and Opera all have btoa() and atob() functions for base 64 encoding and decoding respectively. Mozilla,WebKit和Opera都有btoa()atob()函数,分别用于base 64编码和解码。 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 . 尽可能使用它们,因为它们几乎肯定会比JavaScript实现快得多,并且会回到在进行Web搜索时出现的许多脚本之一。

EDIT 10 SEPTEMBER 2013: atob() and btoa() do not handle Unicode characters outside the ASCII range. 编辑2013年9月10日: atob()btoa()不处理ASCII范围之外的Unicode字符。 MDN has workarounds but I can't vouch for them. MDN有解决方法,但我无法保证。 Thanks to @larspars for pointing this out. 感谢@larspars指出这一点。

For example, if you were using the example from amphetamachine's answer, you could do the following: 例如,如果您使用的是amphetamachine答案中的示例,则可以执行以下操作:

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") );

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;
    }

}

I have part of the code from the answer here: 我从答案中得到了部分代码:

https://scotch.io/quick-tips/how-to-encode-and-decode-strings-with-base64-in-javascript https://scotch.io/quick-tips/how-to-encode-and-decode-strings-with-base64-in-javascript

and the other part from the answer on this page: https://stackoverflow.com/a/3776796/2655623 以及本页答案的另一部分: https//stackoverflow.com/a/3776796/2655623

and here is the result: 这是结果:

var Base64={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(e){var t="";var n,r,i,s,o,u,a;var f=0;e=Base64._utf8_encode(e);while(f<e.length){n=e.charCodeAt(f++);r=e.charCodeAt(f++);i=e.charCodeAt(f++);s=n>>2;o=(n&3)<<4|r>>4;u=(r&15)<<2|i>>6;a=i&63;if(isNaN(r)){u=a=64}else if(isNaN(i)){a=64}t=t+this._keyStr.charAt(s)+this._keyStr.charAt(o)+this._keyStr.charAt(u)+this._keyStr.charAt(a)}return t},decode:function(e){var t="";var n,r,i;var s,o,u,a;var f=0;e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");while(f<e.length){s=this._keyStr.indexOf(e.charAt(f++));o=this._keyStr.indexOf(e.charAt(f++));u=this._keyStr.indexOf(e.charAt(f++));a=this._keyStr.indexOf(e.charAt(f++));n=s<<2|o>>4;r=(o&15)<<4|u>>2;i=(u&3)<<6|a;t=t+String.fromCharCode(n);if(u!=64){t=t+String.fromCharCode(r)}if(a!=64){t=t+String.fromCharCode(i)}}t=Base64._utf8_decode(t);return t},_utf8_encode:function(e){e=e.replace(/\r\n/g,"\n");var t="";for(var n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r)}else if(r>127&&r<2048){t+=String.fromCharCode(r>>6|192);t+=String.fromCharCode(r&63|128)}else{t+=String.fromCharCode(r>>12|224);t+=String.fromCharCode(r>>6&63|128);t+=String.fromCharCode(r&63|128)}}return t},_utf8_decode:function(e){var t="";var n=0;var r=c1=c2=0;while(n<e.length){r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r);n++}else if(r>191&&r<224){c2=e.charCodeAt(n+1);t+=String.fromCharCode((r&31)<<6|c2&63);n+=2}else{c2=e.charCodeAt(n+1);c3=e.charCodeAt(n+2);t+=String.fromCharCode((r&15)<<12|(c2&63)<<6|c3&63);n+=3}}return t}}

window.btoa = function(str) {
    return Base64.encode(str);
}

window.atob = function(str) {
    return Base64.decode(str);
} 

As this keep everything in one place, I won't involve myself with how window.atb / window.btoa act different in various browsers. 由于这将所有内容保存在一个地方,因此我不会介绍window.atb / window.btoa在各种浏览器中的行为方式。

IE 10 & above and all latest browser IE 10及以上版本和所有最新浏览器

Encode String 编码字符串

var str = "raj";
var enc = window.btoa(str); // cmFq

Decode String 解码字符串

var dec = window.atoa('cmFq'); // raj

Or else you might have your own function on page. 否则你可能在页面上有自己的功能。 small blog with references 有参考资料的小博客

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM