Base64 encoding is a method of converting binary data (like images, files, or any non-text data) into ASCII text characters. This allows binary data to be transmitted safely through text-only systems like email, JSON, URLs, and HTML.
Imagine you need to mail a photograph, but the postal service only accepts letters. Base64 is like describing the photo using only letters and numbers so it can be sent safely.
Why is Base64 Used?
- Email Attachments: SMTP only supports text, so files are Base64-encoded
- Embedded Images: Small images in HTML/CSS without separate files
- JSON/XML: Include binary data in text-based formats
- URLs: Safely pass binary data in URL parameters
- Authentication: API tokens and credentials
How Base64 Works
Base64 uses 64 characters to represent data:
- A-Z (26 characters)
- a-z (26 characters)
- 0-9 (10 characters)
- + and / (2 characters)
Example:
- Text:
Hello - Base64:
SGVsbG8=
Common Base64 Use Cases
1. Embedded Images in HTML
<img src="data:image/png;base64,iVBORw0KG...">
Useful for small icons and logos without extra HTTP requests.
2. Email Attachments
Files are Base64-encoded in MIME format when sending emails.
3. Basic Authentication
Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=
(username:password encoded)
4. JWT Tokens
JSON Web Tokens use Base64 URL-safe encoding for security tokens.
Base64 File Size Overhead
Important: Base64 increases file size by approximately 33%
- 10 KB file → 13.3 KB Base64
- 100 KB file → 133 KB Base64
This is because 3 bytes of binary data become 4 characters in Base64.
How to Encode/Decode Base64
Command Line (Linux/Mac)
Encode: base64 file.jpg
Decode: base64 -d encoded.txt > file.jpg
Windows PowerShell
Encode: [Convert]::ToBase64String([IO.File]::ReadAllBytes("file.jpg"))
JavaScript
Encode: btoa("Hello")
Decode: atob("SGVsbG8=")
Python
import base64
encoded = base64.b64encode(b"Hello")
PHP
$encoded = base64_encode("Hello");
$decoded = base64_decode($encoded);
Base64 vs Base64URL
- Base64: Uses +, /, and = (standard)
- Base64URL: Uses -, _, no padding (URL-safe)
Base64URL is used in JWTs and URLs because +, /, and = have special meanings in URLs.
Base64 is NOT encryption! It's just encoding. Anyone can decode it. Never use Base64 alone for sensitive data.
When NOT to Use Base64
- Large images: Use separate files (better caching)
- Security: Use proper encryption, not Base64
- Large datasets: 33% size increase impacts performance