Base64 Encoding Explained: How It Works and When to Use It
Base64 converts binary data into 64 printable ASCII characters. It is not encryption — it solves one problem: safely transmitting binary data through channels that only handle text.
Why Base64 Exists
Early protocols like SMTP were text-only. Binary files (images, PDFs) needed representation as printable characters. Base64 maps every 6 bits to one of 64 safe characters: A-Z, a-z, 0-9, +, /.
How Encoding Works
Input is processed in 3-byte chunks, split into four 6-bit groups. Three bytes always produce four characters — a 33% overhead. The = character pads incomplete final groups.
Encoding "Man":
M=01001101 a=01100001 n=01101110 → Split: 010011|010110|000101|101110 → TWFu
URL-Safe Base64
Replaces + with - and / with _, omits = padding. Used in JWTs, OAuth tokens, and signed cookies to avoid URL encoding conflicts.
Common Uses
Data URLs
Embed images directly: data:[mime];base64,[data]. Useful for small icons where saving an HTTP request outweighs the 33% size cost.
JSON Web Tokens
A JWT has three Base64url-encoded parts: header, payload, signature. The first two are plain JSON — readable by anyone. Never store secrets in JWT payload assuming it is hidden.
HTTP Basic Auth
The Authorization header encodes username:password as Base64. Trivially reversible — always use over HTTPS only.
JavaScript:btoa('Hello') → SGVsbG8=atob('SGVsbG8=') → Hello