Base64
Base64
Three bytes as four characters. MIME, data URLs, PEM.
- Overhead
- +33% on random bytes
- Padding
- = to a whole block
- Standard
- RFC 4648 §4 and §5
- Family
- 1 in base64
Sample
- Out
- aGVsbG8gd29ybGQh
- Back
- "hello world!"
Options
Access
- Import
import { base64 } from "@agntn/encodings/base64" - CLI
encodings encode base64 'hello world!' - Tryplayground with the sample above
The one you've seen a million times. Three bytes, four characters, = to fill the last block.
encode("base64", "hello world!"); // "aGVsbG8gd29ybGQh"
decode("base64", "aGVsbG8g\r\nd29ybGQh").bytes; // "hello world!", line break and all skipped
Decoding skips whitespace, so a MIME body or a PEM block decodes as it is. It takes the text without padding too. The wrong padding, though? Zg= is one = short, and you'll hear about it. A - or _ is an error here, not a guess.
Is YR== valid base64?
Depends who you ask. a is eight bits, YR is twelve, and the four spare bits should be zero. R sets one of them. Decoding shrugs and reads a, same as YQ==. RFC 4648 lets a decoder go either way.
Want the strict answer? canonical: true refuses it and names the character:
decode("base64", "YR==", { canonical: true });
// DecodeError: "R" (U+0052) at index 1 leaves non-zero bits after the last byte
It looks at those bits only, so line breaks and missing padding still pass. The URL alphabet takes it too.
The URL alphabet
+ and / break a URL and a file name. RFC 4648 swaps them for - and _, and alphabet: "url" does the same. JWTs drop the padding on top of that:
encode("base64", '{"alg":"HS256","typ":"JWT"}', { alphabet: "url", padding: false });
// "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9"
Look familiar? Every JWT starts with eyJ, because every JWT starts with {". To read one back, pass the alphabet to decode as well. It takes the padding when it's there.