The short answer: transport, not secrecy
Base64 does one job: turn binary bytes into printable ASCII so they can cross channels that accept only text — email bodies, JSON fields, URLs, HTTP headers. There is no key and anyone can reverse the encoding, so storing a password or token after one pass is equivalent to plaintext. Use real encryption such as AES when confidentiality matters.
The only criterion is whether the downstream channel accepts printable ASCII and nothing else. If it does, encode. If it can take binary or multipart, Base64 adds a third more bytes for no benefit.
Mechanism: 3 bytes in, 4 characters out
Encoding works on groups of 3 bytes (24 bits), split into four 6-bit values, each mapped through a 64-entry alphabet. A short final group is padded with = so the output length is always a multiple of four.
Index Char Index Char Index Char
0-25 A-Z 26-51 a-z 52-61 0-9
62 + 63 / Pad =
Worked example: Man → TWFu
| Step | Value |
|---|---|
| ASCII | M=77, a=97, n=110 |
| Binary | 01001101 01100001 01101110 |
| 6-bit groups | 010011 010110 000101 101110 |
| Decimal | 19, 22, 5, 46 |
| Base64 | TWFu |
Those four groups are what shifting and masking the source bytes produces: the first character takes the top six bits, the next takes the following six, and so on. Decoding packs four 6-bit values back into 24 bits and splits them into bytes.
Expansion and padding cost
Three bytes in, four characters out — exactly 4/3 ≈ 33.3%, and that is a floor rather than a ceiling. Shorter inputs are worse: a single byte still becomes four characters, two of them =, a 300% increase. Encoding many small fields one at a time therefore costs far more than the headline third.
Variant: URL-safe alphabet and = padding
Standard Base64 uses + and /, both ambiguous in a URL: + reads as a space in a query string and / changes path hierarchy. RFC 4648 §5 defines the URL-safe form with - for +, _ for /, and no trailing =.
Two pitfalls that actually bite:
- Pad the length to a multiple of four before decoding. Strict decoders reject a short input outright; lenient ones repair it silently, which is worse because the failure surfaces somewhere else.
- Never cross-decode the two alphabets. Feeding a URL-safe string to a standard decoder fails or produces wrong bytes at
-and_; the usual symptom is a JWT that decodes to gibberish.
A JWT's header and payload are Base64URL:
eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
That is why it can sit unchanged in a URL or HTTP header — and also why it carries no confidentiality, since anyone can decode the middle segment into JSON.
Choosing by scenario
| Scenario | Base64? | Cost and boundary |
|---|---|---|
| Small inline icons as Data URLs | Small assets yes, large no | +1/3 size, no independent caching or lazy loading, slower first paint |
| MIME email attachments | Required | +1/3 size, a CRLF every 76 characters |
| JWT / OAuth state | Required by the format | No secrecy; anyone can decode the payload |
| HTTP Basic Auth | Required by the protocol | Encoding only; credentials decode directly, so TLS must protect the channel |
| Source Map / WASM embedding | Optional | +1/3 size; worth it only for single-file distribution |
Data URLs: the one case that needs arithmetic
A Data URL turns an asset into a string inside HTML or CSS and buys exactly one thing: one fewer HTTP request.
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUg..." alt="logo">
It costs three: text grows by a third; the asset loses individual browser caching, so every HTML change re-downloads every inlined file; and it cannot be lazy-loaded, while the inline payload delays first-paint parsing. Inlining therefore fits only icons that are very small, stable, and on the critical path. The test is the Network panel: compare the request cost of the asset against the bytes it adds to the HTML, and pick the cheaper side.
Three details that actually break
btoa / atob are Latin1-only
btoa('中文') raises InvalidCharacterError because it treats input as single bytes and rejects anything above 0xFF. This legacy one-liner still works:
const encoded = btoa(unescape(encodeURIComponent('中文')));
const decoded = decodeURIComponent(escape(atob(encoded)));
It leans on the old escape / unescape pair; the clearer route is TextEncoder for bytes, then your own mapping onto the alphabet.
Fix the charset before encoding
The same string encoded as UTF-8 and as GBK yields different bytes, hence different Base64. When Chinese text crosses systems, the bug is usually in the charset used before encoding rather than in Base64 itself: normalise to UTF-8 first. To verify, decode the output back to bytes and look for UTF-8 sequences such as E4 B8 AD.
MIME line breaks and database storage
MIME inserts a CRLF every 76 characters. Strip those breaks before handing mail bodies to a generic decoder, or some implementations treat them as invalid input. Storage follows the same logic: a Base64 column is longer than a binary column and inflates indexes, so keep binary when the database supports it.
Per-language reference
| Language | Encode | Decode |
|---|---|---|
| JS (Browser) | btoa(str) |
atob(b64) |
| Node.js | Buffer.from(str).toString('base64') |
Buffer.from(b64, 'base64') |
| Python | base64.b64encode(data) |
base64.b64decode(b64) |
| Go | base64.StdEncoding.EncodeToString(data) |
base64.StdEncoding.DecodeString(b64) |
| Java | Base64.getEncoder().encodeToString(bytes) |
Base64.getDecoder().decode(b64) |
30-second verification
echo -n "hello world" | base64 # → aGVsbG8gd29ybGQ=
echo -n "hello world" | wc -c # → 11
echo -n "aGVsbG8gd29ybGQ=" | base64 -d | wc -c # → 11 (decoded bytes; encoded length is 16 chars = 4/3)
11 bytes become 16 characters, matching 3-bytes-to-4-characters exactly. Change hello world to hello worle, one letter apart, and only the tail of the output changes: Base64 does not obfuscate, it only re-represents. Recheck anytime with the Base64 converter or the file to Base64 tool.