Skip to content

Commit 61b1e45

Browse files
Marc BaquéMarc Baqué
authored andcommitted
fix: normalize base64 decoding for JS library
1 parent e518640 commit 61b1e45

File tree

4 files changed

+234
-498
lines changed

4 files changed

+234
-498
lines changed

Cargo.lock

Lines changed: 27 additions & 16 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

languages/js/Makefile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ proto:
1111
build:
1212
yarn build
1313

14-
dev: build
14+
dev: copy_lib build
1515
yarn start
1616

1717
test: build

languages/js/src/ffi/base64.ts

Lines changed: 2 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -1,68 +1,7 @@
1-
const p = "=";
2-
const tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
3-
41
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"));
313
};
324

335
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")
687
};

0 commit comments

Comments
 (0)