Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix base64 decoding function #2533

Merged
merged 3 commits into from
Jul 19, 2022
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 8 additions & 37 deletions bin/wasm-node/javascript/src/instance/buffer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,42 +60,13 @@ function checkRange(buffer: Uint8Array, offset: number, length: number) {
* The input is assumed to be correct.
*/
export function trustedBase64Decode(base64: string): Uint8Array {
// This implementation was mostly copy-pasted (with some adjustments)
// from <https://developer.mozilla.org/en-US/docs/Glossary/Base64>. As indicated in the
// about section (<https://developer.mozilla.org/en-US/docs/MDN/About>), this code is in the
// public domain.

function b64ToUint6(nChr: number) {
return nChr > 64 && nChr < 91 ?
nChr - 65
: nChr > 96 && nChr < 123 ?
nChr - 71
: nChr > 47 && nChr < 58 ?
nChr + 4
: nChr === 43 ?
62
: nChr === 47 ?
63
:
0;

}

const nInLen = base64.length
const nOutLen = nInLen * 3 + 1 >> 2
const taBytes = new Uint8Array(nOutLen);

for (var nMod3, nMod4, nUint24 = 0, nOutIdx = 0, nInIdx = 0; nInIdx < nInLen; nInIdx++) {
nMod4 = nInIdx & 3;
nUint24 |= b64ToUint6(base64.charCodeAt(nInIdx)) << 6 * (3 - nMod4);
if (nMod4 === 3 || nInLen - nInIdx === 1) {
for (nMod3 = 0; nMod3 < 3 && nOutIdx < nOutLen; nMod3++, nOutIdx++) {
taBytes[nOutIdx] = nUint24 >>> (16 >>> nMod3 & 24) & 255;
}
nUint24 = 0;

}
// This code is a bit sketchy due to the fact that we decode into a string, but it seems to
// work.
const binaryString = atob(base64);
const size = binaryString.length;
const bytes = new Uint8Array(size);
for (let i = 0; i < size; i++) {
bytes[i] = binaryString.charCodeAt(i);
}

return taBytes;
return bytes;
}