From cce84c3782ef4976a14895e882236fa012c1d87f Mon Sep 17 00:00:00 2001 From: n1474335 Date: Wed, 13 Nov 2019 17:59:16 +0000 Subject: [PATCH] Fixed bug in Base62 operations when using different alphabets --- src/core/operations/FromBase62.mjs | 17 ++++++++++++----- src/core/operations/ToBase62.mjs | 9 ++++++--- 2 files changed, 18 insertions(+), 8 deletions(-) diff --git a/src/core/operations/FromBase62.mjs b/src/core/operations/FromBase62.mjs index c2f54ec0..9e91f647 100644 --- a/src/core/operations/FromBase62.mjs +++ b/src/core/operations/FromBase62.mjs @@ -42,15 +42,22 @@ class FromBase62 extends Operation { */ run(input, args) { if (input.length < 1) return []; - const ALPHABET = Utils.expandAlphRange(args[0]).join(""); - const BN = BigNumber.clone({ ALPHABET }); + const alphabet = Utils.expandAlphRange(args[0]).join(""); + const BN62 = BigNumber.clone({ ALPHABET: alphabet }); - const re = new RegExp("[^" + ALPHABET.replace(/[[\]\\\-^$]/g, "\\$&") + "]", "g"); + const re = new RegExp("[^" + alphabet.replace(/[[\]\\\-^$]/g, "\\$&") + "]", "g"); input = input.replace(re, ""); - const number = new BN(input, 62); + // Read number in using Base62 alphabet + const number = new BN62(input, 62); + // Copy to new BigNumber object that uses the default alphabet + const normalized = new BigNumber(number); - return Utils.convertToByteArray(number.toString(16), "Hex"); + // Convert to hex and add leading 0 if required + let hex = normalized.toString(16); + if (hex.length % 2 !== 0) hex = "0" + hex; + + return Utils.convertToByteArray(hex, "Hex"); } } diff --git a/src/core/operations/ToBase62.mjs b/src/core/operations/ToBase62.mjs index c5d2f35e..a00d9275 100644 --- a/src/core/operations/ToBase62.mjs +++ b/src/core/operations/ToBase62.mjs @@ -44,12 +44,15 @@ class ToBase62 extends Operation { input = new Uint8Array(input); if (input.length < 1) return ""; - const ALPHABET = Utils.expandAlphRange(args[0]).join(""); - const BN = BigNumber.clone({ ALPHABET }); + const alphabet = Utils.expandAlphRange(args[0]).join(""); + const BN62 = BigNumber.clone({ ALPHABET: alphabet }); input = toHexFast(input).toUpperCase(); - const number = new BN(input, 16); + // Read number in as hex using normal alphabet + const normalized = new BigNumber(input, 16); + // Copy to BigNumber clone that uses the specified Base62 alphabet + const number = new BN62(normalized); return number.toString(62); }