Base64
Base64 (RFC 4648) writes bytes as text: every 3 bytes become 4 characters from a 64-letter alphabet, 6 bits each. A last group of 1 or 2 bytes becomes 2 or 3 characters, padded with = to 4. Apps use it for keys, certificates (PEM), tokens (JWT), images in data URLs and binary data in JSON.
- Standard alphabet:
A–Z a–z 0–9 + /, with = padding.
- URL-safe:
- and _ instead of + and /, usually without padding (JWTs, URLs, file names).
- MIME breaks lines every 76 characters, PEM every 64.
The page decodes either alphabet and ignores whitespace and padding.
1The Base64 library
lib/base64.js is a JavaScript module with no dependencies; it exports Base64, a class of static methods, and works in pages, workers and jsc.
import { Base64 } from "../lib/base64.js";
const text = Base64.encode(bytes); // standard, padded
const token = Base64.encode(bytes, { urlSafe: true }); // URL-safe, no padding
const back = Base64.decode(text); // Uint8Array
| Method | What it does |
| Base64.encode(bytes, { urlSafe, padding, lineLength }) | Base64 text. padding defaults to true, false when urlSafe; lineLength breaks lines (76 for MIME, 64 for PEM). |
| Base64.decode(text, { ignoreInvalid }) | The bytes. Accepts both alphabets and ignores whitespace and =; other characters throw, unless ignoreInvalid. |
| Base64.encodeText(text), Base64.decodeText(base64) | The same for UTF-8 text. |
| Base64.STANDARD, Base64.URL_SAFE | The two alphabets. |
2The Bytes library
lib/bytes.js (no dependencies) exports Bytes, the small byte helpers the other libraries share, as static methods.
import { Bytes } from "../lib/bytes.js";
Bytes.toHex(Bytes.concat([first, second]), ":");
| Method | What it does |
| Bytes.toHex(bytes, separator) | "0a1b2c", or "0a:1b:2c" with ":". |
| Bytes.fromHex(text) | Bytes from hex; spaces, colons and a leading 0x are ignored. |
| Bytes.concat(arrays), Bytes.equal(first, second) | Join byte arrays; compare them. |
| Bytes.from(input) | A Uint8Array view of an ArrayBuffer, typed array or DataView. |
| Bytes.random(count) | Random bytes (crypto.getRandomValues). |
| Bytes.readUintBE / readUintLE(bytes, offset, size) | An unsigned integer of up to 6 bytes. |