const _mask = 31; const _shift = 5 export function decodeBase32(accountId: string): Buffer{ return fromBase32String(accountId); } export function encodeBase32(data: Buffer): string{ let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; const padding = false; const length = data.byteLength; const view = new Uint8Array(data); let bits = 0; let value = 0; let output = ''; for (let i = 0; i < length; i++) { value = (value << 8) | view[i]!; bits += 8; while (bits >= 5) { output += alphabet[(value >>> (bits - 5)) & 31]; bits -= 5; } } if (bits > 0) { output += alphabet[(value << (5 - bits)) & 31]; } if (padding) { while (output.length % 8 !== 0) { output += '='; } } return output; } function charToInt(c: string): number{ switch (c) { case 'A': return 0; case 'B': return 1; case 'C': return 2; case 'D': return 3; case 'E': return 4; case 'F': return 5; case 'G': return 6; case 'H': return 7; case 'I': return 8; case 'J': return 9; case 'K': return 10; case 'L': return 11; case 'M': return 12; case 'N': return 13; case 'O': return 14; case 'P': return 15; case 'Q': return 16; case 'R': return 17; case 'S': return 18; case 'T': return 19; case 'U': return 20; case 'V': return 21; case 'W': return 22; case 'X': return 23; case 'Y': return 24; case 'Z': return 25; case '2': return 26; case '3': return 27; case '4': return 28; case '5': return 29; case '6': return 30; case '7': return 31; } return -1; } function fromBase32String(encoded: string): Buffer{ if(encoded == null) { throw Error("Invalid data"); }; encoded = encoded.trim().toUpperCase(); if(encoded.length == 0){ return Buffer.alloc(0); } let outLength = encoded.length * _shift /8; let result = Buffer.alloc(outLength); let buffer = 0; let next = 0; let bitsLeft = 0; let charValue = 0; for(let c of encoded){ charValue = charToInt(c); if(charValue < 0) { throw Error("Illegal character: '" + c + "'"); } buffer <<= _shift; buffer |= charValue & _mask; bitsLeft += _shift; if(bitsLeft >= 8){ result[next++] = buffer >> (bitsLeft - 8); bitsLeft -=8; } } return result; }