What Is Base64?
Base64 is a binary-to-text encoding scheme that represents binary data as ASCII characters. It converts every 3 bytes of input into 4 printable characters from a 64-character alphabet:
AβZ (26)
aβz (26)
0β9 (10)
+ (1)
/ (1)
= (padding)
The result is about 33% larger than the original but is guaranteed to be safe to transmit through any system that handles text.
How Encoding Works
Base64 processes input 3 bytes at a time, converting each group into 4 characters:
Input: M a n
Binary: 01001101 01100001 01101110
Groups: 010011 010110 000101 101110
Decimal: 19 22 5 46
Output: T W F u
If the input length isn't a multiple of 3, = padding is added:
- 1 leftover byte β 2 Base64 chars +
== - 2 leftover bytes β 3 Base64 chars +
=
Base64 vs Base64URL
Standard Base64 uses + and /, which have special meaning in URLs. Base64URL replaces them:
| Standard Base64 | Base64URL |
|---|---|
+ | - |
/ | _ |
= (padding) | omitted |
Base64URL is used in JWTs, URL-safe identifiers, and any context where the encoded string appears in a URL or HTTP header.
// Standard Base64
btoa("hello+world") // "aGVsbG8rd29ybGQ="
// Base64URL (manual conversion)
btoa("hello+world")
.replace(/\+/g, "-")
.replace(/\//g, "_")
.replace(/=+$/, "")
When to Use Base64
β Good use cases
Embedding binary in text protocols:
<!-- Inline image in HTML/CSS -->
<img src="data:image/png;base64,iVBORw0KGgo...">
Storing binary data in JSON:
{
"avatar": "data:image/jpeg;base64,/9j/4AAQSkZJRgAB..."
}
HTTP Basic Authentication:
Authorization: Basic dXNlcjpwYXNzd29yZA==
(This is user:password Base64-encoded β note: not encrypted, just encoded)
Email attachments (MIME): Email was originally ASCII-only. Base64 encodes binary attachments so they survive SMTP transport.
Environment variables with special characters:
export DB_CONFIG=$(echo '{"host":"db","pass":"p@$$!"}' | base64)
β Wrong use cases
"Securing" data: Base64 is trivially reversible β it's not encryption or obfuscation. Never use it to hide passwords or sensitive data.
Optimizing storage: The 33% overhead makes Base64 a bad fit for large binary blobs in databases. Use a blob/bytea column instead.
Hiding credentials in code: Base64-encoded credentials in source code are just as exposed as plaintext.