Base32 Encoding and Decoding for UTF-8 Text

Encode UTF-8 text with the RFC 4648 Base32 alphabet, add correct padding, and decode back while rejecting invalid characters.

JavascriptSecurity Boundaries

Code

javascriptsnippet
41 lines
const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";

export function base32Encode(input) {
  if (typeof input !== "string") throw new TypeError("input must be a string");
  const bytes = new TextEncoder().encode(input);
  let bits = 0;
  let value = 0;
  let output = "";
  for (const byte of bytes) {
    value = (value << 8) | byte;
    bits += 8;
    while (bits >= 5) {
      output += ALPHABET[(value >>> (bits - 5)) & 31];
      bits -= 5;
    }
  }
  if (bits > 0) output += ALPHABET[(value << (5 - bits)) & 31];
  while (output.length % 8 !== 0) output += "=";
  return output;
}

export function base32Decode(input) {
  if (typeof input !== "string") throw new TypeError("input must be a string");
  const normalized = input.toUpperCase().replace(/=+$/, "");
  if (!/^[A-Z2-7]*$/.test(normalized)) {
    throw new RangeError("invalid base32 characters");
  }
  let bits = 0;
  let value = 0;
  const bytes = [];
  for (const char of normalized) {
    const index = ALPHABET.indexOf(char);
    value = (value << 5) | index;
    bits += 5;
    if (bits >= 8) {
      bytes.push((value >>> (bits - 8)) & 255);
      bits -= 8;
    }
  }
  return new TextDecoder().decode(new Uint8Array(bytes));
}

How it works

Count the functions base32Encode and base32Decode as the entire surface area of Base32 Encoding and Decoding for UTF-8 Text.

The nesting pairs for (const byte of bytes) with while (bits >= 5) — the inner runs once per outer step. When the guard condition holds, TypeError and RangeError is thrown rather than a bogus value returned.

A fresh value is allocated for the result; the arguments stay untouched.

What to watch for

  • The guard typeof input !== "string" short-circuits the flow with an early throw when its condition holds.

Applying it

Signature: export function base32Encode(input)

base32Encode is what another module would consume; nothing else here is load-bearing for callers.

Statements that matter

if (typeof input !== "string") throw new TypeError("input must be a string");
if (bits > 0) output += ALPHABET[(value << (5 - bits)) & 31];
return new TextDecoder().decode(new Uint8Array(bytes));

Interactive Tools for This Topic

FAQ

Does `base32Encode` modify its input?
The input survives unchanged; what you get back is a newly constructed value.
Does the code validate its input?
The code refuses to continue: `TypeError` and `RangeError` is thrown while the state is still recoverable.
Does the runtime need any help from npm, pip, cargo, or the like?
No — the package manager has nothing to do here; nothing is declared. The file defines `base32Encode`, `base32Decode` at load time.