diff --git a/src/engine/operations/encodings.ts b/src/engine/operations/encodings.ts index 8a60779..b2cc7e6 100644 --- a/src/engine/operations/encodings.ts +++ b/src/engine/operations/encodings.ts @@ -64,6 +64,7 @@ function fromBase85(text: string, alphabet: string): Uint8Array { if (group.length === 5) { let value = 0; for (const digit of group) value = value * 85 + digit; + if (value > 0xffffffff) throw new OperationError('Base85 group is out of range.'); out.push((value >>> 24) & 0xff, (value >>> 16) & 0xff, (value >>> 8) & 0xff, value & 0xff); group = []; } @@ -74,6 +75,7 @@ function fromBase85(text: string, alphabet: string): Uint8Array { for (let i = 0; i < padding; i++) group.push(84); let value = 0; for (const digit of group) value = value * 85 + digit; + if (value > 0xffffffff) throw new OperationError('Base85 group is out of range.'); const bytes = [(value >>> 24) & 0xff, (value >>> 16) & 0xff, (value >>> 8) & 0xff, value & 0xff]; out.push(...bytes.slice(0, 4 - padding)); } @@ -120,7 +122,9 @@ function fromBase45(text: string): Uint8Array { if (value > 0xffff) throw new OperationError('Base45 group is out of range.'); out.push(value >> 8, value & 0xff); } else if (i + 1 < digits.length) { - out.push(digits[i]! + digits[i + 1]! * 45); + const value = digits[i]! + digits[i + 1]! * 45; + if (value > 0xff) throw new OperationError('Base45 group is out of range.'); + out.push(value); } else { throw new OperationError('Base45 input has a trailing incomplete group.'); } diff --git a/src/engine/tests/operations.verified.test.ts b/src/engine/tests/operations.verified.test.ts index 5f5dc5a..72c4830 100644 --- a/src/engine/tests/operations.verified.test.ts +++ b/src/engine/tests/operations.verified.test.ts @@ -496,6 +496,20 @@ describe('edge cases the property tests turned up', () => { expect(await text('BB8\n', 'from-base45')).toBe('AB'); }); + it('Base45 refuses a two-digit group above one byte instead of wrapping it', async () => { + expect(toHex(await bytesOut('U5', 'from-base45'))).toBe('ff'); + expect(await refusal('ZZ', 'from-base45')).toMatch(/out of range/); + expect(await refusal('BB8::', 'from-base45')).toMatch(/out of range/); + }); + + it('Base85 refuses a group above 32 bits instead of wrapping it', async () => { + expect(toHex(await bytesOut('s8W-!', 'from-base85'))).toBe('ffffffff'); + expect(await refusal('s8W-"', 'from-base85')).toMatch(/out of range/); + expect(await refusal('uuuuu', 'from-base85')).toMatch(/out of range/); + expect(await refusal('uuu', 'from-base85')).toMatch(/out of range/); + expect(await refusal('%%%%%', ['from-base85', { Alphabet: 'Z85' }])).toMatch(/out of range/); + }); + it('Base58 turns each leading 1 into one zero byte, and nothing into nothing', async () => { expect(await bytesOut('', 'from-base58')).toBe(''); expect(toHex(await bytesOut('1', 'from-base58'))).toBe('00');