Base64 Encoder: How It Works
Base64 turns arbitrary bytes into 64 safe printable characters so binary data can travel through systems built for text. It is an encoding, not encryption — anyone can reverse it instantly, and treating it as protection is a genuine security mistake.
How it works
Base64 takes three bytes — 24 bits — and re-groups them into four 6-bit values, each mapped to a character from A–Z a–z 0–9 + /. Because 6 bits give 64 possibilities, every combination has a printable representation.
When the input is not a multiple of three bytes, the output is padded with = characters. This is why encoded strings so often end in one or two equals signs, and why the length is always a multiple of four.
| Input | Bytes | Output | Padding |
|---|---|---|---|
Man | 3 | TWFu | none |
Ma | 2 | TWE= | one |
M | 1 | TQ== | two |
The 33% cost
Four output characters for every three input bytes means base64 is about 33% larger than the original, plus any line breaks. That overhead is the price of text safety, and it is why base64 is right for small payloads and wrong for large ones. Embedding a 2 MB image as a data URI produces 2.7 MB of markup that cannot be cached separately from the page.
Standard versus URL-safe
Standard base64 uses + and /, both of which have meaning in URLs — + is decoded as a space in query strings and / is a path separator. URL-safe base64 substitutes - and _ and usually drops the padding.
This variant is what JWTs use, which is why a JWT segment pasted into a standard decoder sometimes fails. If decoding produces garbage, converting - to + and _ to / and restoring padding almost always fixes it.
Where it is genuinely used
- Email attachments — SMTP was designed for 7-bit text, so MIME encodes binary parts in base64.
- Data URIs — small icons and fonts embedded directly in CSS or HTML to avoid a request.
- HTTP Basic authentication —
username:passwordencoded in a header. Note that this is encoding for transport, not protection; Basic auth is only safe over HTTPS. - JWTs and API tokens — the URL-safe variant.
- Binary fields in JSON and XML, neither of which can carry raw bytes.
The mistake worth naming
Base64 provides no confidentiality whatsoever. Anyone can decode it in a browser console in one line. Encoded credentials in a configuration file, an API key in a request header, or a 'hidden' identifier in a URL are all fully readable. If something must be protected, encrypt it; if it must be verified, sign it. Base64 solves transport, not security.
Text and encoding
Base64 operates on bytes, not characters. Encoding text requires deciding on a character encoding first — nearly always UTF-8. A string containing non-ASCII characters encoded as UTF-8 and then base64 produces different output than the same string encoded as Latin-1. If a decoded result shows mangled accents or emoji, an encoding mismatch upstream is the usual cause.