-
Notifications
You must be signed in to change notification settings - Fork 0
/
base64shared.js
48 lines (41 loc) · 1.28 KB
/
base64shared.js
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
// https://datatracker.ietf.org/doc/html/rfc4648
export function encode64(bytes, alphabet, paddingChar) {
if (typeof bytes == "string") bytes = new TextEncoder().encode(bytes);
if (bytes instanceof ArrayBuffer) bytes = new Uint8Array(bytes);
let bits = 0;
let accumulator = 0;
const output = [];
let index = 0;
while (index < bytes.length || bits > 0) {
if (bits < 6 && index < bytes.length) {
accumulator = (accumulator << 8) | bytes[index++];
bits += 8;
}
output.push((accumulator << 6) >> bits);
bits -= 6;
}
let padding = paddingChar ? "".padStart(-bits / 2, paddingChar) : "";
return output.map((v) => alphabet[v & 0x3f]).join('') + padding;
}
export function decode64(string, alphabet, paddingChar) {
let bits = 0;
let accumulator = 0;
const output = [];
let index = 0;
while (index < string.length) {
if (bits < 8 && index < string.length) {
let char = string[index++];
if (char != paddingChar) {
let found = alphabet.indexOf(char);
if (found < 0) throw new Error(`Character not known: ${char}`);
accumulator = (accumulator << 6) | found;
bits += 6;
}
}
if (bits >= 8) {
output.push((accumulator << 8) >> bits);
bits -= 8;
}
}
return new Uint8Array(output);
}