Functional Weave
Code in TypeScript

encoding.base32@1.0.0

README.md

1,608 bytes · view raw

# encoding.base32

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.

**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).