Base64: how it works and when to use it
The byte-to-character mechanics behind Base64, why padding exists, which alphabet variants you will meet, and the boundaries where Base64 is the wrong tool.
问题
The byte-to-character mechanics behind Base64, why padding exists, which alphabet variants you will meet, and the boundaries where Base64 is the wrong tool.
Pasos
-
1. The core mechanic: 3 bytes become 4 characters
Base64 works in 6-bit groups. Three bytes are 24 bits, and 24 bits split into four 6-bit values, each mapped to one of 64 printable characters (A–Z, a–z, 0–9, + and / in the standard alphabet). That is why encoded output is always a multiple of 4 characters and roughly 4/3 the size of the input — the size increase is the price of surviving text-only channels like JSON strings, XML, SMTP, and data URLs.
-
2. Why padding exists
Real data is rarely a multiple of 3 bytes. With one leftover byte (8 bits), only 14 bits are usable — two characters carry 12 of them, and the last two bits are zero-padded before a '=' is appended. Two leftover bytes produce three characters plus '='. A length that is 2 or 3 modulo 4 therefore needs one or two '=' characters; strict decoders reject anything else, and the most common decode failure is simply a missing '=' that got trimmed by a query-parameter parser.
-
3. The alphabet variants you will actually meet
The standard alphabet uses '+' and '/', which are unsafe inside URLs and filenames. The URL-safe variant replaces them with '-' and '_'. JWTs use the URL-safe alphabet without padding. MIME Base64 (email attachments) keeps the standard alphabet but inserts CRLF every 76 characters and ignores other whitespace when decoding. When a string fails to decode, the alphabet is the first thing to check — the same payload is not interchangeable between variants without conversion.
-
4. What Base64 is not
Base64 provides zero confidentiality: it is a deterministic, key-less transformation anyone can reverse. It also is not compression — it grows data. Its legitimate uses are transport (binary through text channels) and embedding (data: URLs, inline assets). If you need confidentiality, encrypt first and then Base64 the ciphertext if the channel requires text.
-
5. Performance and storage notes
Encoding and decoding are cheap (single-pass, cache-friendly), but the 33% size growth applies to storage and memory too: a 30MB file becomes a 40MB string, and JSON-embedding it copies that string again. For large binary payloads, prefer multipart bodies or object storage references; reserve Base64 for small artifacts — icons, tokens, certificates, short blobs.
Resultado esperado
You can trace any Base64 string back to its bytes, explain why padding exists, pick the right alphabet variant for URLs or MIME, and recognize when Base64 is being misused as compression, encryption, or a transport for large payloads.