Base64 是一種把二進位資料改用 64 個可列印字元表示的編碼方式,常用於在只接受文字的地方傳遞資料,例如把圖片塞進 JSON、在網址或 HTML 屬性中帶值。它不是加密,只是編碼——任何人都能還原,所以別拿它保護機敏資訊。
<script type="text/javascript"> var base64encodechars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; var base64decodechars = new Array( -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1);
解碼表是一張以字元編碼為索引的查表,對應位置存它的 6 位數值,不在表內的字元(含換行、空白)一律標成 -1,解碼時直接跳過。
function base64encode(str) {
var out, i, len;
var c1, c2, c3;
len = str.length;
i = 0;
out = "";
while (i < len) {
c1 = str.charCodeAt(i++) & 0xff;
if (i == len) { // 剩 1 個位元組,補 "=="
out += base64encodechars.charAt(c1 >> 2);
out += base64encodechars.charAt((c1 & 0x3) << 4);
out += "==";
break;
}
c2 = str.charCodeAt(i++);
if (i == len) { // 剩 2 個位元組,補 "="
out += base64encodechars.charAt(c1 >> 2);
out += base64encodechars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xf0) >> 4));
out += base64encodechars.charAt((c2 & 0xf) << 2);
out += "=";
break;
}
c3 = str.charCodeAt(i++);
out += base64encodechars.charAt(c1 >> 2);
out += base64encodechars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xf0) >> 4));
out += base64encodechars.charAt(((c2 & 0xf) << 2) | ((c3 & 0xc0) >> 6));
out += base64encodechars.charAt(c3 & 0x3f);
}
return out;
}
每三個位元組(24 位元)切成四段 6 位元,各自對應一個編碼字元;不足三個位元組時用 = 補齊,這就是 Base64 為什麼長度一定是 4 的倍數。
function base64decode(str) {
var c1, c2, c3, c4;
var i, len, out;
len = str.length;
i = 0;
out = "";
while (i < len) {
do {
c1 = base64decodechars[str.charCodeAt(i++) & 0xff];
} while (i < len && c1 == -1);
if (c1 == -1) break;
do {
c2 = base64decodechars[str.charCodeAt(i++) & 0xff];
} while (i < len && c2 == -1);
if (c2 == -1) break;
out += String.fromCharCode((c1 << 2) | ((c2 & 0x30) >> 4));
do {
c3 = str.charCodeAt(i++) & 0xff;
if (c3 == 61) return out; // 遇到 '=' 就結束
c3 = base64decodechars[c3];
} while (i < len && c3 == -1);
if (c3 == -1) break;
out += String.fromCharCode(((c2 & 0xf) << 4) | ((c3 & 0x3c) >> 2));
do {
c4 = str.charCodeAt(i++) & 0xff;
if (c4 == 61) return out;
c4 = base64decodechars[c4];
} while (i < len && c4 == -1);
if (c4 == -1) break;
out += String.fromCharCode(((c3 & 0x03) << 6) | c4);
}
return out;
}
</script>
今天的瀏覽器都內建了 btoa() 與 atob(),處理純 ASCII 字串一行就夠:
btoa("hello"); // "aGVsbG8="
atob("aGVsbG8="); // "hello"
但遇到中文會出問題,因為這兩個函式只吃 Latin-1。處理 UTF-8 中文要經過一層轉換:
btoa(unescape(encodeURIComponent("你好")));
decodeURIComponent(escape(atob(encoded)));
上面這份手寫實作的價值在於完整展示了位元運算的過程:每個步驟的位移與遮罩,正好對應 Base64 的 6-bit 分組規則,讀懂之後再回頭看內建函式就會很透徹。