/
base64.js.es6
79 lines (68 loc) · 2.04 KB
/
base64.js.es6
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
/**
* @var {String} BASE64 Alphabet of Base64 encoding.
*/
const BASE64 =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
/**
* Converts a Base64 string to an bytes array.
*
* @param {String} str
*
* @return {Uint8Array}
*/
export function base64ToBuffer(str) {
let length = str.length;
while (str.charAt(length - 1) === "=") {
--length;
}
length = Math.floor((length / 4) * 3);
let ret = new Uint8Array(length);
/* eslint-disable no-bitwise */
for (let i = 0, j = 0; i < length; i += 3) {
let enc1 = BASE64.indexOf(str.charAt(j++));
let enc2 = BASE64.indexOf(str.charAt(j++));
let enc3 = BASE64.indexOf(str.charAt(j++));
let enc4 = BASE64.indexOf(str.charAt(j++));
ret[i] = (enc1 << 2) | (enc2 >> 4);
if (enc3 !== 64) ret[i + 1] = ((enc2 & 15) << 4) | (enc3 >> 2);
if (enc4 !== 64) ret[i + 2] = ((enc3 & 3) << 6) | enc4;
}
/* eslint-enable no-bitwise */
return ret;
}
/**
* Converts a bytes array to a Base64 string.
*
* @param {ArrayBuffer} buffer
*
* @return {String}
*/
export function bufferToBase64(buffer) {
let ret = "";
let bytes = new Uint8Array(buffer);
let length = bytes.byteLength - (bytes.byteLength % 3);
/* eslint-disable no-bitwise */
for (let i = 0; i < length; i = i + 3) {
let bits = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];
let enc1 = (bits >> 18) & 63;
let enc2 = (bits >> 12) & 63;
let enc3 = (bits >> 6) & 63;
let enc4 = bits & 63;
ret += BASE64[enc1] + BASE64[enc2] + BASE64[enc3] + BASE64[enc4];
}
length = bytes.byteLength;
if (length % 3 === 1) {
let bits = bytes[length - 1];
let enc1 = (bits >> 2) & 63;
let enc2 = (bits << 4) & 63;
ret += BASE64[enc1] + BASE64[enc2] + "==";
} else if (length % 3 === 2) {
let bits = (bytes[length - 2] << 8) | bytes[length - 1];
let enc1 = (bits >> 10) & 63;
let enc2 = (bits >> 4) & 63;
let enc3 = (bits << 2) & 63;
ret += BASE64[enc1] + BASE64[enc2] + BASE64[enc3] + "=";
}
/* eslint-enable no-bitwise */
return ret;
}