Base64 Explained: How It Works and Why It Is Not Encryption
Base64 is a way of writing any sequence of bytes (an image, a key, UTF-8 text) using only 64 safe characters: A to Z, a to z, 0 to 9, + and /, plus = for padding. It exists because many systems were built to carry text, not arbitrary bytes: email bodies, JSON strings, URLs, HTTP headers. Base64 lets binary data pass through them unchanged.
The one thing to remember: Base64 is an encoding, not encryption. It has no key. Anyone who sees a Base64 string can turn it back into the original bytes in one step, so it protects nothing.
Examples use Python 3.10 or later, Node.js 22 or later, and the base64 command found on Linux and macOS. The format is defined in RFC 4648.
How it works
Base64 reads the input three bytes (24 bits) at a time and splits those 24 bits into four groups of 6 bits. Six bits can hold a number from 0 to 63, and each number picks one character from the alphabet: 0 is A, 25 is Z, 26 is a, 51 is z, 52 is 0, 61 is 9, 62 is + and 63 is /. This script does it by hand for the text "Man" and checks the result against the standard library:
import base64
data = b"Man"
bits = "".join(f"{byte:08b}" for byte in data)
groups = [bits[i:i + 6] for i in range(0, len(bits), 6)]
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
print(bits)
print(groups, [int(g, 2) for g in groups])
print("".join(alphabet[int(g, 2)] for g in groups))
print(base64.b64encode(data))
for text in [b"Ma", b"M"]:
print(text, "->", base64.b64encode(text))
010011010110000101101110
['010011', '010110', '000101', '101110'] [19, 22, 5, 46]
TWFu
b'TWFu'
b'Ma' -> b'TWE='
b'M' -> b'TQ=='
When the input is not a multiple of three bytes, the last group is filled with zero bits and the output is padded with = so its length is always a multiple of four: two bytes give one =, one byte gives two.
That gives the size rule: every 3 bytes become 4 characters, so Base64 output is about 33% larger than the input (exactly 4 × ceil(n / 3) characters for n bytes, with padding). A 30 KB image becomes about 40 KB of text.
Where you meet it
- Data URLs:
data:image/png;base64,iVBORw0KGgo...embeds a small file directly in HTML or CSS. - Email attachments: MIME encodes attachments in Base64, wrapped in lines of at most 76 characters.
- HTTP Basic authentication: the header
Authorization: Basiccarriesusername:passwordin Base64. Because that is readable by anyone who sees the request, Basic auth is only acceptable over HTTPS. - JSON Web Tokens (JWTs): the header and payload are Base64url, so anyone holding a token can read its contents. The signature proves who issued it; it does not hide anything.
- Binary data in JSON or XML, and PEM files (the
-----BEGIN ...-----blocks for certificates and keys).
Base64 in Python
Base64 works on bytes, so text must be encoded first, normally as UTF-8. Forgetting this is the most common error: base64.b64encode("text") fails with TypeError: a bytes-like object is required, not 'str'.
import base64
import binascii
text = "Café €"
raw = text.encode("utf-8") # str -> bytes first
encoded = base64.b64encode(raw).decode("ascii")
print(len(raw), "bytes ->", encoded, f"({len(encoded)} chars)")
decoded = base64.b64decode(encoded, validate=True).decode("utf-8")
print(decoded == text)
# URL-safe alphabet: - and _ instead of + and /
blob = bytes([251, 255, 190])
print(base64.b64encode(blob), base64.urlsafe_b64encode(blob))
# Bad input raises binascii.Error instead of returning garbage
try:
base64.b64decode("TWFu!", validate=True)
except binascii.Error as err:
print("binascii.Error:", err)
9 bytes -> Q2Fmw6kg4oKs (12 chars)
True
b'+/++' b'-_--'
binascii.Error: Only base64 data is allowed
validate=True makes decoding reject characters outside the alphabet; without it, Python silently skips them, which can hide corrupted input.
The URL-safe variant
+ and / have special meanings in URLs and file names, so RFC 4648 also defines "base64url", which uses - and _ instead. It is often used without the = padding, as in JWTs. Decoding with the wrong alphabet fails or produces wrong bytes, so check which variant a system expects.
Base64 in JavaScript
// Node.js: Buffer handles UTF-8 and both alphabets
const encoded = Buffer.from("Café €", "utf8").toString("base64");
console.log(encoded);
console.log(Buffer.from(encoded, "base64").toString("utf8"));
console.log(Buffer.from([251, 255, 190]).toString("base64url"));
// Browser (also works in Node): btoa only accepts characters 0-255,
// so convert the text to UTF-8 bytes first
function toBase64(text) {
const bytes = new TextEncoder().encode(text);
return btoa(Array.from(bytes, (b) => String.fromCharCode(b)).join(""));
}
function fromBase64(b64) {
const bytes = Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
return new TextDecoder().decode(bytes);
}
console.log(toBase64("Café €"), fromBase64(toBase64("Café €")));
Q2Fmw6kg4oKs
Café €
-_--
Q2Fmw6kg4oKs Café €
The browser functions btoa and atob only handle characters with codes 0 to 255. btoa("€") throws InvalidCharacterError, and btoa("café") "works" but encodes the é as one Latin-1 byte rather than UTF-8, giving Y2Fm6Q== where every other tool gives Y2Fmw6k=. Converting through TextEncoder, as above, avoids both problems.
On the command line
printf '%s' 'Man' | base64 # TWFu
echo 'Man' | base64 # TWFuCg== (echo added a newline)
printf '%s' 'TWFu' | base64 -d # Man
echo adds a newline, which gets encoded too: use printf '%s'. GNU base64 on Linux wraps long output at 76 characters; add -w 0 for one line. To check a value quickly without a terminal, the Base64 Converter encodes and decodes UTF-8 text in both alphabets, in your browser.
Encoding is not encryption
Because decoding needs no key, Base64 offers no confidentiality at all. Decoding the payload of a JWT takes two lines:
import base64
import json
# The middle part of a JWT (header.PAYLOAD.signature)
payload = "eyJzdWIiOiIxMjM0Iiwicm9sZSI6ImFkbWluIiwiZXhwIjoxNzk1ODAwMDAwfQ"
padded = payload + "=" * (-len(payload) % 4) # JWTs drop the padding
print(json.loads(base64.urlsafe_b64decode(padded)))
{'sub': '1234', 'role': 'admin', 'exp': 1795800000}
So:
- Never use Base64 to "hide" passwords, API keys or personal data in code, configuration files, URLs or databases. A secret that is Base64-encoded in a Git repository is a leaked secret.
- Never store passwords in Base64. Passwords are stored with a slow password-hashing function such as Argon2id; see storing passwords safely in Python.
- Do not put sensitive data in a JWT payload unless the token is also encrypted.
- For confidentiality, use encryption: HTTPS (TLS) for data in transit, and an authenticated encryption scheme from a well-reviewed library, with the key kept outside the code, for data at rest.
Keep the three ideas apart: an encoding (Base64, URL encoding, UTF-8) changes the representation and is reversible by anyone; a hash is a one-way fingerprint (see hash functions and checksums); encryption is reversible only with a key.
Common mistakes
- Encoding text without choosing a character set. Always encode to UTF-8 bytes first, and decode the result as UTF-8. Character encoding and UTF-8 explains why.
- Missing padding.
binascii.Error: Incorrect paddingusually means the string was cut short or came from a source that drops=; add padding back to a multiple of four, as in the JWT example. - Mixing the standard and URL-safe alphabets.
- Encoding twice. If the decoded output is itself Base64, something encoded it twice.
- Using Base64 for large files in JSON when the API supports uploading the raw file: the extra third adds up.