From 834ff95702ea0cf3b145c213d192d70a1807add1 Mon Sep 17 00:00:00 2001 From: n1474335 Date: Tue, 15 Oct 2019 16:25:52 +0100 Subject: [PATCH] Base64 operations now throw a meaningful error if the alphabet is the wrong length --- src/core/lib/Base64.mjs | 8 +++++++- tests/node/tests/operations.mjs | 8 ++++---- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/src/core/lib/Base64.mjs b/src/core/lib/Base64.mjs index 7730ae07..339a41d4 100644 --- a/src/core/lib/Base64.mjs +++ b/src/core/lib/Base64.mjs @@ -7,7 +7,7 @@ */ import Utils from "../Utils.mjs"; - +import OperationError from "../errors/OperationError.mjs"; /** * Base64's the input byte array using the given alphabet, returning a string. @@ -33,6 +33,9 @@ export function toBase64(data, alphabet="A-Za-z0-9+/=") { } alphabet = Utils.expandAlphRange(alphabet).join(""); + if (alphabet.length !== 64 && alphabet.length !== 65) { // Allow for padding + throw new OperationError(`Invalid Base64 alphabet length (${alphabet.length}): ${alphabet}`); + } let output = "", chr1, chr2, chr3, @@ -86,6 +89,9 @@ export function fromBase64(data, alphabet="A-Za-z0-9+/=", returnType="string", r alphabet = alphabet || "A-Za-z0-9+/="; alphabet = Utils.expandAlphRange(alphabet).join(""); + if (alphabet.length !== 64 && alphabet.length !== 65) { // Allow for padding + throw new OperationError(`Invalid Base64 alphabet length (${alphabet.length}): ${alphabet}`); + } const output = []; let chr1, chr2, chr3, diff --git a/tests/node/tests/operations.mjs b/tests/node/tests/operations.mjs index 42ba74c9..8337c48d 100644 --- a/tests/node/tests/operations.mjs +++ b/tests/node/tests/operations.mjs @@ -885,17 +885,17 @@ smothering ampersand abreast it("toBase64: editableOption", () => { const result = toBase64("some input", { alphabet: { - value: "0-9A-W" + value: "0-9A-W+/a-zXYZ=" }, }); - assert.strictEqual(result.toString(), "SPI1R1T0"); + assert.strictEqual(result.toString(), "StXkPI1gRe1sT0=="); }), it("toBase64: editableOptions key is value", () => { const result = toBase64("some input", { - alphabet: "0-9A-W", + alphabet: "0-9A-W+/a-zXYZ=", }); - assert.strictEqual(result.toString(), "SPI1R1T0"); + assert.strictEqual(result.toString(), "StXkPI1gRe1sT0=="); }), it("toBase64: editableOptions default", () => {