|
1 | | -const p = "="; |
2 | | -const tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; |
3 | | - |
4 | 1 | export const base64ToBytes = (base64: string): Uint8Array => { |
5 | | - // summary |
6 | | - // Convert a base64-encoded string to an array of bytes |
7 | | - var s = base64.split(""), |
8 | | - out = []; |
9 | | - var l = s.length; |
10 | | - while (s[--l] === p) {} // strip off trailing padding |
11 | | - for (var i = 0; i < l; ) { |
12 | | - var t = tab.indexOf(s[i++]) << 18; |
13 | | - if (i <= l) { |
14 | | - t |= tab.indexOf(s[i++]) << 12; |
15 | | - } |
16 | | - if (i <= l) { |
17 | | - t |= tab.indexOf(s[i++]) << 6; |
18 | | - } |
19 | | - if (i <= l) { |
20 | | - t |= tab.indexOf(s[i++]); |
21 | | - } |
22 | | - out.push((t >>> 16) & 0xff); |
23 | | - out.push((t >>> 8) & 0xff); |
24 | | - out.push(t & 0xff); |
25 | | - } |
26 | | - // strip off any null bytes |
27 | | - while (out[out.length - 1] === 0) { |
28 | | - out.pop(); |
29 | | - } |
30 | | - return new Uint8Array(out); // byte[] |
| 2 | + return new Uint8Array(Buffer.from(base64, "base64")); |
31 | 3 | }; |
32 | 4 |
|
33 | 5 | export const bytesToBase64 = (bytes: Uint8Array): string => { |
34 | | - // summary |
35 | | - // Encode an array of bytes as a base64-encoded string |
36 | | - var t; |
37 | | - var s = [], |
38 | | - l = bytes.length; |
39 | | - var rm = l % 3; |
40 | | - var x = l - rm; |
41 | | - for (var i = 0; i < x; ) { |
42 | | - t = (bytes[i++] << 16) | (bytes[i++] << 8) | bytes[i++]; |
43 | | - s.push(tab.charAt((t >>> 18) & 0x3f)); |
44 | | - s.push(tab.charAt((t >>> 12) & 0x3f)); |
45 | | - s.push(tab.charAt((t >>> 6) & 0x3f)); |
46 | | - s.push(tab.charAt(t & 0x3f)); |
47 | | - } |
48 | | - // deal with trailers, based on patch from Peter Wood. |
49 | | - switch (rm) { |
50 | | - case 2: { |
51 | | - t = (bytes[i++] << 16) | (bytes[i++] << 8); |
52 | | - s.push(tab.charAt((t >>> 18) & 0x3f)); |
53 | | - s.push(tab.charAt((t >>> 12) & 0x3f)); |
54 | | - s.push(tab.charAt((t >>> 6) & 0x3f)); |
55 | | - s.push(p); |
56 | | - break; |
57 | | - } |
58 | | - case 1: { |
59 | | - t = bytes[i++] << 16; |
60 | | - s.push(tab.charAt((t >>> 18) & 0x3f)); |
61 | | - s.push(tab.charAt((t >>> 12) & 0x3f)); |
62 | | - s.push(p); |
63 | | - s.push(p); |
64 | | - break; |
65 | | - } |
66 | | - } |
67 | | - return s.join(""); // string |
| 6 | + return Buffer.from(bytes).toString("base64") |
68 | 7 | }; |
0 commit comments