使用 js 进行Base64编码、解码(js-base64)
从IE10+浏览器开始,所有浏览器就原生提供了Base64编码、解码方法,不仅可以用于浏览器环境,Service Worker环境也可以使用。 方法名就是 atob 和 btoa ,具体语法如下:
window.btoa('china is so nb') // 编码
"Y2hpbmEgaXMgc28gbmI="
window.atob("Y2hpbmEgaXMgc28gbmI=") // 解码
"china is so nb"
1
2
3
4
2
3
4
开源的 base64.js ,使用很简单,浏览器引入该JS文件,然后Base64编码这样:
Base64.encode('china is so nb'); // 编码
"Y2hpbmEgaXMgc28gbmI="
1
2
2
解码就调用 decode方法,如下:
Base64.decode("Y2hpbmEgaXMgc28gbmI="); // 解码
'china is so nb'
1
2
2
# 使用 npm 安装
npm install --save js-base64
1
# ES6 Module 引入
import { Base64 } from 'js-base64';
// or if you prefer no Base64 namespace
import { encode, decode } from 'js-base64';
1
2
3
2
3
# common 引入
const {Base64} = require('js-base64');
1
# 使用方法
let latin = 'dankogai';
let utf8 = '小飼弾'
let u8s = new Uint8Array([100,97,110,107,111,103,97,105]);
Base64.encode(latin); // ZGFua29nYWk=
Base64.encode(latin, true)); // ZGFua29nYWk skips padding
Base64.encodeURI(latin)); // ZGFua29nYWk
Base64.btoa(latin); // ZGFua29nYWk=
Base64.btoa(utf8); // raises exception
Base64.fromUint8Array(u8s); // ZGFua29nYWk=
Base64.fromUint8Array(u8s, true); // ZGFua29nYW which is URI safe
Base64.encode(utf8); // 5bCP6aO85by+
Base64.encode(utf8, true) // 5bCP6aO85by-
Base64.encodeURI(utf8); // 5bCP6aO85by-
Base64.decode( 'ZGFua29nYWk=');// dankogai
Base64.decode( 'ZGFua29nYWk'); // dankogai
Base64.atob( 'ZGFua29nYWk=');// dankogai
Base64.atob( '5bCP6aO85by+');// 'å°é£¼å¼¾' which is nonsense
Base64.toUint8Array('ZGFua29nYWk=');// u8s above
Base64.decode( '5bCP6aO85by+');// 小飼弾
// note .decodeURI() is unnecessary since it accepts both flavors
Base64.decode( '5bCP6aO85by-');// 小飼弾
Base64.isValid(0); // false: 0 is not string
Base64.isValid(''); // true: a valid Base64-encoded empty byte
Base64.isValid('ZA=='); // true: a valid Base64-encoded 'd'
Base64.isValid('Z A='); // true: whitespaces are okay
Base64.isValid('ZA'); // true: padding ='s can be omitted
Base64.isValid('++'); // true: can be non URL-safe
Base64.isValid('--'); // true: or URL-safe
Base64.isValid('+-'); // false: can't mix both
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
26
27
28
29
30
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# base64.js 源码
/**
* Created by SLICE_30_K on 2017/5/22.
*
* 支持一般Base64的编码和解码
* 支持符合RFC_4648标准中"URL and Filename Safe Alphabet"的URL安全Base64编解码
* 支持中文字符的编解码(Unicode编码)
*/
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory();
}
else if (typeof define === "function" && define.amd) {
// AMD
define(factory);
}
else {
// Global (browser)
window.BASE64 = factory();
}
}(this, function () {
var BASE64_MAPPING = [
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '+', '/'
];
var URLSAFE_BASE64_MAPPING = [
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '-', '_'
];
var _toBinary = function (ascii) {
var binary = [];
while (ascii > 0) {
var b = ascii % 2;
ascii = Math.floor(ascii / 2);
binary.push(b);
}
binary.reverse();
return binary;
};
var _toDecimal = function (binary) {
var dec = 0;
var p = 0;
for (var i = binary.length - 1; i >= 0; --i) {
var b = binary[i];
if (b == 1) {
dec += Math.pow(2, p);
}
++p;
}
return dec;
};
var _toUTF8Binary = function (c, binaryArray) {
var mustLen = (8 - (c + 1)) + ((c - 1) * 6);
var fatLen = binaryArray.length;
var diff = mustLen - fatLen;
while (--diff >= 0) {
binaryArray.unshift(0);
}
var binary = [];
var _c = c;
while (--_c >= 0) {
binary.push(1);
}
binary.push(0);
var i = 0, len = 8 - (c + 1);
for (; i < len; ++i) {
binary.push(binaryArray[i]);
}
for (var j = 0; j < c - 1; ++j) {
binary.push(1);
binary.push(0);
var sum = 6;
while (--sum >= 0) {
binary.push(binaryArray[i++]);
}
}
return binary;
};
var _toBinaryArray = function (str) {
var binaryArray = [];
for (var i = 0, len = str.length; i < len; ++i) {
var unicode = str.charCodeAt(i);
var _tmpBinary = _toBinary(unicode);
if (unicode < 0x80) {
var _tmpdiff = 8 - _tmpBinary.length;
while (--_tmpdiff >= 0) {
_tmpBinary.unshift(0);
}
binaryArray = binaryArray.concat(_tmpBinary);
} else if (unicode >= 0x80 && unicode <= 0x7FF) {
binaryArray = binaryArray.concat(_toUTF8Binary(2, _tmpBinary));
} else if (unicode >= 0x800 && unicode <= 0xFFFF) {//UTF-8 3byte
binaryArray = binaryArray.concat(_toUTF8Binary(3, _tmpBinary));
} else if (unicode >= 0x10000 && unicode <= 0x1FFFFF) {//UTF-8 4byte
binaryArray = binaryArray.concat(_toUTF8Binary(4, _tmpBinary));
} else if (unicode >= 0x200000 && unicode <= 0x3FFFFFF) {//UTF-8 5byte
binaryArray = binaryArray.concat(_toUTF8Binary(5, _tmpBinary));
} else if (unicode >= 4000000 && unicode <= 0x7FFFFFFF) {//UTF-8 6byte
binaryArray = binaryArray.concat(_toUTF8Binary(6, _tmpBinary));
}
}
return binaryArray;
};
var _toUnicodeStr = function (binaryArray) {
var unicode;
var unicodeBinary = [];
var str = "";
for (var i = 0, len = binaryArray.length; i < len;) {
if (binaryArray[i] == 0) {
unicode = _toDecimal(binaryArray.slice(i, i + 8));
str += String.fromCharCode(unicode);
i += 8;
} else {
var sum = 0;
while (i < len) {
if (binaryArray[i] == 1) {
++sum;
} else {
break;
}
++i;
}
unicodeBinary = unicodeBinary.concat(binaryArray.slice(i + 1, i + 8 - sum));
i += 8 - sum;
while (sum > 1) {
unicodeBinary = unicodeBinary.concat(binaryArray.slice(i + 2, i + 8));
i += 8;
--sum;
}
unicode = _toDecimal(unicodeBinary);
str += String.fromCharCode(unicode);
unicodeBinary = [];
}
}
return str;
};
var _encode = function (str, url_safe) {
var base64_Index = [];
var binaryArray = _toBinaryArray(str);
var dictionary = url_safe ? URLSAFE_BASE64_MAPPING : BASE64_MAPPING;
var extra_Zero_Count = 0;
for (var i = 0, len = binaryArray.length; i < len; i += 6) {
var diff = (i + 6) - len;
if (diff == 2) {
extra_Zero_Count = 2;
} else if (diff == 4) {
extra_Zero_Count = 4;
}
var _tmpExtra_Zero_Count = extra_Zero_Count;
while (--_tmpExtra_Zero_Count >= 0) {
binaryArray.push(0);
}
base64_Index.push(_toDecimal(binaryArray.slice(i, i + 6)));
}
var base64 = '';
for (var i = 0, len = base64_Index.length; i < len; ++i) {
base64 += dictionary[base64_Index[i]];
}
for (var i = 0, len = extra_Zero_Count / 2; i < len; ++i) {
base64 += '=';
}
return base64;
};
var _decode = function (_base64Str, url_safe) {
var _len = _base64Str.length;
var extra_Zero_Count = 0;
var dictionary = url_safe ? URLSAFE_BASE64_MAPPING : BASE64_MAPPING;
if (_base64Str.charAt(_len - 1) == '=') {
if (_base64Str.charAt(_len - 2) == '=') {//两个等号说明补了4个0
extra_Zero_Count = 4;
_base64Str = _base64Str.substring(0, _len - 2);
} else {//一个等号说明补了2个0
extra_Zero_Count = 2;
_base64Str = _base64Str.substring(0, _len - 1);
}
}
var binaryArray = [];
for (var i = 0, len = _base64Str.length; i < len; ++i) {
var c = _base64Str.charAt(i);
for (var j = 0, size = dictionary.length; j < size; ++j) {
if (c == dictionary[j]) {
var _tmp = _toBinary(j);
/*不足6位的补0*/
var _tmpLen = _tmp.length;
if (6 - _tmpLen > 0) {
for (var k = 6 - _tmpLen; k > 0; --k) {
_tmp.unshift(0);
}
}
binaryArray = binaryArray.concat(_tmp);
break;
}
}
}
if (extra_Zero_Count > 0) {
binaryArray = binaryArray.slice(0, binaryArray.length - extra_Zero_Count);
}
var str = _toUnicodeStr(binaryArray);
return str;
};
var __BASE64 = {
encode: function (str) {
return _encode(str, false);
},
decode: function (base64Str) {
return _decode(base64Str, false);
},
urlsafe_encode: function (str) {
return _encode(str, true);
},
urlsafe_decode: function (base64Str) {
return _decode(base64Str, true);
}
};
return __BASE64;
}));
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
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
上次更新: 2024/01/30, 00:35:17
- 02
- Node与GLIBC_2.27不兼容解决方案08-19
- 03
- Git清空本地文件跟踪缓存08-13