Base32 encoding is everywhere — TOTP secret keys, file IDs, DNS labels. Here is a clean browser-only implementation.
Try it: https://devnestio.pages.dev/base32-encoder/
Encode
function base32Encode(input, alphabet, addPadding) {
const bytes = new TextEncoder().encode(input);
let bits = 0, value = 0, out = "";
for (const byte of bytes) {
value = (value << 8) | byte;
bits += 8;
while (bits >= 5) {
out += alphabet[(value >>> (bits - 5)) & 31];
bits -= 5;
}
}
if (bits > 0) out += alphabet[(value << (5 - bits)) & 31];
if (addPadding) while (out.length % 8 !== 0) out += "=";
return out;
}
Decode
function base32Decode(input, alphabet) {
const clean = input.toUpperCase().replace(/=+$/, "").replace(/\s/g, "");
let bits = 0, value = 0;
const bytes = [];
for (const c of clean) {
const idx = alphabet.indexOf(c);
if (idx < 0) throw new Error("Invalid char: " + c);
value = (value << 5) | idx;
bits += 5;
if (bits >= 8) { bytes.push((value >>> (bits - 8)) & 0xff); bits -= 8; }
}
return new TextDecoder().decode(new Uint8Array(bytes));
}
Features
- Standard (RFC 4648) and Hex (Base32Hex) alphabets
- Optional
=padding - Overhead and padding statistics
- Reference table for all 32 values
DevNestio — browser-only developer tools.
Top comments (0)