JavaScript用btoa和atob來編碼解碼Base64

JavaScript用btoa和atob來編碼解碼Base64

btoa和atob是window物件的兩個函式,其中btoa是binary to ascii,用於將binary的資料用ascii碼錶示,即Base64的編碼過程,而atob則是ascii to binary,用於將ascii碼解析成binary資料,看一個例子:

// Define the string
var string = 'Hello World!';
// Encode the String
var encodedString = btoa(string);
console.log(encodedString); // Outputs: "SGVsbG8gV29ybGQh"
// Decode the String
var decodedString = atob(encodedString);
console.log(decodedString); // Outputs: "Hello World!"

可以看到,字串“Hello World!”已被Base64編碼和解碼。但是,atob和btoa不能編碼Unicode字元:

var string = "Hello, 中國!";
window.btoa(string);

那如何用這種方式支援漢字呢?這裡我們可以先將帶有非Latin1字元的串先用encodeURIComponent編碼:

var string = "Hello, 中國!";
//"SGVsbG8lMkMlMjAlRTQlQjglQUQlRTUlOUIlQkQlRUYlQkMlODE="
var encodedString = btoa(encodeURIComponent(string));
var decodedString = decodeURIComponent(atob(encodedString));
console.log(decodedString); //"Hello, 中國!"

注意,編碼的過程是先encodeURI,再編碼,那麼解碼的過程應該是先解碼,再decodeURI。另外,在使用atob和btoa這兩個函式時需要注意的是,IE9是不支援的,在IE11中,用模擬工具切換到IE9模式,然後直接在控制檯呼叫btoa方法:

如果在IE中使用,需要IE版本為10及以上(以下是IE10的效果):

正是因為IE9不支援atob和btoa,我們才需要為相容IE9而使用無奈之舉:使用公共類庫:

// Create Base64 Object
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(/rn/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}}
// Define the string
var string = 'Hello World!';
// Encode the String
var encodedString = Base64.encode(string);
console.log(encodedString); // Outputs: "SGVsbG8gV29ybGQh"
// Decode the String
var decodedString = Base64.decode(encodedString);
console.log(decodedString); // Outputs: "Hello World!"

這個自定義的Base64物件可以轉碼的字元也不僅限於Latin1字元:

var string = "Hello, 中國!";
var encodedString = Base64.encode(string);//"SGVsbG8sIOS4reWbve 8gQ=="
var decodedString = Base64.decode(encodedString);
console.log(decodedString); //"Hello, 中國!"

參考頁面:

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