encoding.base32
Bytes to RFC 4648 base32 text (A-Z, 2-7) and back, strictly, as authenticator-app secrets are written.
1.0.0 · published 2026-10-10 by charlie · Anterra
Pinned by 36 tests, run in TypeScript, Python and Rust.base32Encode 14 · base32Decode 22
What it does
Base32 from RFC 4648 section 6: the alphabet `A`-`Z` then `2`-`7`, five bits per character, eight characters for every five bytes. It is the form authenticator apps use for TOTP secrets (`JBSWY3DPEHPK3PXP`), and `auth.totp` builds on it. `base32Encode(utf8Encode("foobar"), true)` is `MZXW6YTBOI======`; with `padding` false it is `MZXW6YTBOI`.
Bytes are lists of integers 0 to 255, as everywhere in the registry.
The functions
A group: 2 functions that work together, each in its own file, each pinned by its own tests in TypeScript, Python and Rust. A project can install only the ones it calls.
- base32_encode (bytes: int[], padding: bool) -> string
- base32_decode (text: string) -> int[]
Once installed, your code imports each one from the group's module.
base32_encode throws on bad input 14 tests
pub fn base32_encode(bytes: &[i64], padding: bool) -> String
| bytes | int[] | each an integer from 0 to 255 |
| padding | bool | true pads with = to a multiple of 8 characters; false leaves it off, as otpauth:// secrets do |
| returns | string | upper-case letters A-Z and digits 2-7 |
For example
base32_encode(, true)→ RFC 4648 section 10: '' paddedbase32_encode(102, true)→ MY====== RFC 4648 section 10: 'f' paddedbase32_encode(102, 111, true)→ MZXQ==== RFC 4648 section 10: 'fo' padded
fune!(encoding.base32@^1); // then call base32_encode(…)
Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
use super::funejson::Value; ← the fune runtime: the JSON value the test vectors use; fune build keeps it only where a signature takes one
const ALPHABET: &[u8; 32] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
/// Bytes as RFC 4648 base32: five bits per character, upper case, padded
/// with = to a multiple of eight characters when `padding` is true.
///
/// # Panics
/// Panics if any value is outside 0-255.
pub fn base32_encode(bytes: &[i64], padding: bool) -> String {
let mut out = String::with_capacity(bytes.len() * 8 / 5 + 8);
let mut buffer: u32 = 0;
let mut bits = 0;
for &b in bytes {
if !(0..=255).contains(&b) {
panic!("bytes must be a list of integers from 0 to 255");
}
buffer = ((buffer << 8) | b as u32) & 0xfff;
bits += 8;
while bits >= 5 {
out.push(ALPHABET[((buffer >> (bits - 5)) & 31) as usize] as char);
bits -= 5;
}
}
if bits > 0 {
out.push(ALPHABET[((buffer << (5 - bits)) & 31) as usize] as char);
}
if padding {
while out.len() % 8 != 0 {
out.push('=');
}
}
out
}
pub fn fune_vector(args: &[Value]) -> Value {
let bytes: Vec<i64> = match &args[0] {
Value::Arr(items) => items
.iter()
.map(|item| match item {
Value::Int(i) => *i,
_ => panic!("bytes must be a list of integers from 0 to 255"),
})
.collect(),
_ => panic!("bytes must be a list of integers from 0 to 255"),
};
let padding = match &args[1] {
Value::Bool(b) => *b,
_ => panic!("padding must be true or false"),
};
Value::str(&base32_encode(&bytes, padding))
}base32_decode throws on bad input 22 tests
pub fn base32_decode(text: &str) -> Vec<i64>
| text | string | A-Z and 2-7 in either case, with or without correct = padding; no spaces or hyphens |
| returns | int[] | one integer from 0 to 255 per byte |
For example
base32_decode()→ RFC 4648 section 10: '' paddedbase32_decode(MY======)→ 102 RFC 4648 section 10: 'f' paddedbase32_decode(MZXQ====)→ 102, 111 RFC 4648 section 10: 'fo' padded
fune!(encoding.base32@^1); // then call base32_decode(…)
Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
use super::funejson::Value; ← the fune runtime: the JSON value the test vectors use; fune build keeps it only where a signature takes one
/// Padding that each count of data characters past a multiple of 8 needs;
/// -1 marks the counts no byte string produces.
const PAD: [i64; 8] = [0, -1, 6, -1, 4, 3, -1, 1];
fn quintet(c: char) -> i64 {
match c {
'A'..='Z' => c as i64 - 65,
'a'..='z' => c as i64 - 97,
'2'..='7' => c as i64 - 24,
_ => -1,
}
}
/// RFC 4648 base32 back to bytes. Either case; = padding optional but exact
/// when present; no spaces or other characters; zero bits after the last
/// byte.
///
/// # Panics
/// Panics on a character outside the alphabet, padding that is wrong or not
/// at the end, an impossible length, or non-zero trailing bits.
pub fn base32_decode(text: &str) -> Vec<i64> {
let mut values: Vec<u32> = Vec::with_capacity(text.len());
let mut padding = 0i64;
for c in text.chars() {
if c == '=' {
padding += 1;
continue;
}
let v = quintet(c);
if v < 0 || padding > 0 {
panic!("base32 text may only contain A-Z and 2-7, with = padding at the end");
}
values.push(v as u32);
}
let rest = values.len() % 8;
if PAD[rest] < 0 {
panic!("base32 text has a length that no byte count produces");
}
if padding > 0 && padding != PAD[rest] {
panic!("base32 text has the wrong amount of = padding");
}
let mut out = Vec::with_capacity(values.len() * 5 / 8);
let mut buffer: u32 = 0;
let mut bits = 0;
for v in values {
buffer = ((buffer << 5) | v) & 0x1fff;
bits += 5;
if bits >= 8 {
out.push(((buffer >> (bits - 8)) & 255) as i64);
bits -= 8;
}
}
if buffer & ((1u32 << bits) - 1) != 0 {
panic!("base32 text has non-zero bits after its last byte");
}
out
}
pub fn fune_vector(args: &[Value]) -> Value {
let text = match &args[0] {
Value::Str(s) => s.as_str(),
_ => panic!("base32 text must be a string"),
};
Value::Arr(base32_decode(text).into_iter().map(Value::Int).collect())
}Install
fune build
With that line in your source, in a Rust project (language rust in fune.project), fune build resolves it and nothing else, pins them in fune.lock, downloads only the Rust package of each, and builds the code above into your project’s .fune/build, one readable file per capability with a header linking back here. A crate’s build.rs runs it before every compile. Or pin a range in fune.project and build in one step:
fune add encoding.base32
That builds the whole group. To build only what you call, and whatever it uses inside the group:
fune add encoding.base32 --only base32Encode
The manifest, vectors and README with only the Rust implementation. Install it without the registry with fune add ./encoding.base32-1.0.0-rust.fune, or fetch it from a terminal with fune pull encoding.base32@1.0.0:rust.
The whole function, every language, is one file too: encoding.base32-1.0.0.fune, 20,209 bytes, sha256 9378a1db5600fc863794e0a7e0bc114a9e04ddc9ef558aefedec326d34434604. It installs into a project of any language.
Customise it in your app
The seams this capability offers. Put a marker directly above a function of your own and fune build wires it into the built code; the package on the registry is not changed, the built file’s header lists it under CUSTOMISED, and fune hooks lists every hook in the project. How hooks work.
before — your function gets the arguments and returns them, changed or not, or throws to refuse the call.
// fune: before encoding.base32.base32Encode
// fune: before encoding.base32.base32Decode
after — your function gets the result and the arguments, and returns the final result.
// fune: after encoding.base32.base32Encode
// fune: after encoding.base32.base32Decode
replace — it requires no other capability, so there is no dependency to replace.
step — your function runs at a numbered point inside a function’s body, receives the in-scope values it names as parameters, and may return replacements. List the points with fune show encoding.base32 --steps.
// fune: step encoding.base32.<fn> after <n|label>
Tests
A version published now needs at least 8 tests for every function, and one that expects the error for each function that throws; the registry refuses it otherwise. fune verify --all runs each case in TypeScript, Python and Rust, and a project runs them again with fune verify. This page lists the cases; it does not run them. The exact JSON is vectors.json.
base32Encode 14 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| RFC 4648 section 10: '' padded | , true | → | |
| RFC 4648 section 10: 'f' padded | 102, true | → | MY====== |
| RFC 4648 section 10: 'fo' padded | 102, 111, true | → | MZXQ==== |
| RFC 4648 section 10: 'foo' padded | 102, 111, 111, true | → | MZXW6=== |
| RFC 4648 section 10: 'foob' padded | 102, 111, 111, 98, true | → | MZXW6YQ= |
| RFC 4648 section 10: 'fooba' padded | 102, 111, 111, 98, 97, true | → | MZXW6YTB |
| RFC 4648 section 10: 'foobar' padded | 102, 111, 111, 98, 97, 114, true | → | MZXW6YTBOI====== |
| RFC 4648 'f' without padding, as otpauth:// writes secrets | 102, false | → | MY |
| RFC 4648 'foobar' without padding, as otpauth:// writes secrets | 102, 111, 111, 98, 97, 114, false | → | MZXW6YTBOI |
| the RFC 4226 HOTP test secret, 20 bytes, needs no padding | 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, false | → | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ |
Show the other 4 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| every bit set (hand-checked: five 0xff bytes are eight 7s) | 255, 255, 255, 255, 255, true | → | 77777777 |
| a byte above 255 | 256, true | → | error: bytes must be a list of integers from 0 to 255 |
| a fractional byte | 1.5, false | → | error: bytes must be a list of integers from 0 to 255 |
| padding given as text | 1, yes | → | error: padding must be true or false |
base32Decode 22 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| RFC 4648 section 10: '' padded | → | ||
| RFC 4648 section 10: 'f' padded | MY====== | → | 102 |
| RFC 4648 section 10: 'fo' padded | MZXQ==== | → | 102, 111 |
| RFC 4648 section 10: 'foo' padded | MZXW6=== | → | 102, 111, 111 |
| RFC 4648 section 10: 'foob' padded | MZXW6YQ= | → | 102, 111, 111, 98 |
| RFC 4648 section 10: 'fooba' padded | MZXW6YTB | → | 102, 111, 111, 98, 97 |
| RFC 4648 section 10: 'foobar' padded | MZXW6YTBOI====== | → | 102, 111, 111, 98, 97, 114 |
| "foobar" without padding | MZXW6YTBOI | → | 102, 111, 111, 98, 97, 114 |
| lower case is read as upper case | mzxw6ytboi====== | → | 102, 111, 111, 98, 97, 114 |
| the RFC 4226 HOTP test secret | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ | → | 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48 |
Show the other 12 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| a space between groups is not skipped | MZXW 6YTB | → | error: base32 text may only contain A-Z and 2-7, with = padding at the end |
| a hyphen is not skipped | MZXW-6YTB | → | error: base32 text may only contain A-Z and 2-7, with = padding at the end |
| 0, 1, 8 and 9 are not in the alphabet | MZXW0YTB | → | error: base32 text may only contain A-Z and 2-7, with = padding at the end |
| a trailing newline | MZXW6YTBOI | → | error: base32 text may only contain A-Z and 2-7, with = padding at the end |
| an Arabic-Indic digit is not 2-7 | MZXW٢YTB | → | error: base32 text may only contain A-Z and 2-7, with = padding at the end |
| a character after the padding | MY======A | → | error: base32 text may only contain A-Z and 2-7, with = padding at the end |
| one character past a block: no byte count is 5 bits | MZXW6YTBO | → | error: base32 text has a length that no byte count produces |
| three characters: no byte count is 15 bits | MZX | → | error: base32 text has a length that no byte count produces |
| padding of the wrong length | MY===== | → | error: base32 text has the wrong amount of = padding |
| padding on whole blocks | MZXW6YTB======== | → | error: base32 text has the wrong amount of = padding |
| non-zero bits after the last byte ("M3" would also read as "f") | M3====== | → | error: base32 text has non-zero bits after its last byte |
| a number instead of text | 42 | → | error: base32 text must be a string |
Verification
Verified by the operator, not the sandbox 36 test vectors declared; none run by the registry.
Verified locally by the registry's operator, not by the sandbox. This version was published with FUNE_VERIFY_MODE=inline-dev (the operator's import of the first-party registry, or a development server): the server validated the package - its manifest, signatures, imports, safety lint and test rules - but the registry did not run its test vectors in its sandbox. The operator runs them with `fune verify --all` before importing.
Signed by the registry with key fw-9dc887227da47575 (ed25519), over its integrity and this report's digest. The full report · JSON
More from the author
**Decoding is strict, but forgiving about case and padding.**
- Lower-case letters are read as upper-case: people type secrets. - Padding is optional (the otpauth:// format leaves it off), but padding that is present must be exactly right for the length, at the end, and bring the text to a multiple of eight characters. - Spaces, hyphens, line breaks and anything outside the alphabet are errors, not skipped (RFC 4648 section 3.3). Apps that show a secret in groups of four (`JBSW Y3DP EHPK 3PXP`) should strip the spaces before decoding. - A length no byte count produces (1, 3 or 6 characters past a multiple of eight) is an error, and so are non-zero bits after the last byte (`"MZ"` is "f", `"M3"` is refused), so every byte string has exactly one spelling (section 3.5).
This is the RFC 4648 alphabet, not "base32hex" (section 7), Crockford's or z-base-32. Characters are checked before the length, so the answer for non-ASCII input does not depend on how a language counts its length.
Source: RFC 4648, The Base16, Base32, and Base64 Data Encodings, sections 6, 3.3, 3.5 and the test vectors in section 10 (https://www.rfc-editor.org/rfc/rfc4648).
Files
| Path | Bytes |
|---|---|
| README.md | 1,608 |
| impl/python/base32_decode.py | 1,807 |
| impl/python/base32_encode.py | 1,074 |
| impl/rust/base32_decode.rs | 2,101 |
| impl/rust/base32_encode.rs | 1,629 |
| impl/typescript/base32_decode.ts | 1,688 |
| impl/typescript/base32_encode.ts | 1,092 |
| vectors.json | 5,354 |