Base64 operations now throw a meaningful error if the alphabet is the wrong length

This commit is contained in:
n1474335 2019-10-15 16:25:52 +01:00
parent 3472484601
commit 834ff95702
2 changed files with 11 additions and 5 deletions

View File

@ -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,

View File

@ -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", () => {