Base64 Encoding Explained: How It Works, With Tested Code
Base64 encoding turns any bytes into text made of 64 safe characters, so binary data can travel through JSON, email, URLs and HTTP headers. See the bit-level steps, padding, URL-safe base64, the 33% size cost and common errors, with Python and JavaScript code we ran.
- Base64 encoding maps every 3 bytes to 4 characters from an alphabet of 64: A to Z, a to z, 0 to 9, plus
+and/. =padding fills the last block. “Hello” becomesSGVsbG8=.- Output is about 33% larger than input. Our 1,000,000 byte test became 1,333,336 characters.
- URL-safe base64 swaps
+and/for-and_. Base64 is not encryption: anyone can decode it.
You have seen strings like SGVsbG8= in API responses, email source, JWTs and data: URLs. That is base64 encoding, one of the most common formats in software. It lets binary data, such as images, keys or compressed files, travel through systems that only handle text safely.
This guide explains how it works at the bit level, why the output grows, which variant to use where, and the errors you will meet. All Python output comes from Python 3.13.6 and all JavaScript output from Node.js 24.22.1.
What is base64 encoding?
Base64 is a binary-to-text encoding defined in RFC 4648. It represents any sequence of bytes using only 64 printable ASCII characters, plus = for padding. Decoding gives back exactly the original bytes, so nothing is lost. It is an encoding, like UTF-8, not compression and not encryption.
Why base64 exists
Many protocols were designed for text. Email (SMTP) historically carried 7-bit ASCII only. JSON has no byte type. HTTP headers and URLs reserve certain characters. Sending raw bytes through them could corrupt data, because a byte might look like a line ending, a quote or a control character. Base64 sidesteps all of that by using characters that every system treats as plain text.
How base64 works, step by step
Take the three bytes of the word Man. In binary they are:
01001101 01100001 01101110
Base64 regroups those 24 bits into four groups of 6 bits, and each 6-bit number (0 to 63) picks one character from the alphabet:
010011 010110 000101 101110
19 22 5 46
T W F u
So Man becomes TWFu. We confirmed both the bit groups and the result in Python. The alphabet runs A to Z (0 to 25), a to z (26 to 51), 0 to 9 (52 to 61), then + (62) and / (63). That is the whole algorithm: 8-bit bytes in, 6-bit characters out.
Padding with =
Input does not always come in multiples of 3 bytes. When the last block is short, base64 pads the output with = so the length is always a multiple of 4:
b'Man' -> b'TWFu'
b'Ma' -> b'TWE='
b'M' -> b'TQ=='
b'Hello' -> b'SGVsbG8='
One leftover byte gives two =, two leftover bytes give one. Some systems, including JWTs, strip the padding. To decode such a string you can add it back with "=" * (-len(s) % 4), as shown in the errors section.
The 33% size cost
Every 3 bytes become 4 characters, so output is four thirds of the input. We measured it:
| Input bytes | Base64 characters | Ratio |
|---|---|---|
| 3 | 4 | 1.333 |
| 30 | 40 | 1.333 |
| 3,000 | 4,000 | 1.333 |
| 1,000,000 | 1,333,336 | 1.333 |
That overhead matters. Embedding a 300 KB image as a base64 data URI adds about 100 KB, and the browser cannot cache it separately. For large files, upload the raw bytes with multipart form data instead of base64 inside JSON.
URL-safe base64 (base64url)
The standard alphabet uses + and /, which have special meaning in URLs and file paths. The URL-safe variant from RFC 4648 section 5 swaps them for - and _:
b'hi?>' standard: b'aGk/Pg==' url-safe: b'aGk_Pg=='
bytes 250-255 (6 bytes) standard: b'+vv8/f7/' url-safe: b'-vv8_f7_'
Use base64url in URLs, cookies, file names and tokens. JWTs use it without padding. We encoded a JWT header and got eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9, the familiar eyJ start of every token. Our JWT guide explains the rest of the token.
Tip: mixing the two variants is a classic bug. A standard decoder treats - and _ as junk, and a URL-safe decoder does the same with + and /. Agree on one variant in your API docs.
Base64 in Python
The standard library base64 module works on bytes, not strings. Encode text to bytes first, usually as UTF-8:
import base64
data = "नमस्ते €".encode("utf-8")
enc = base64.b64encode(data)
print(enc)
# b'4KSo4KSu4KS44KWN4KSk4KWHIOKCrA=='
print(base64.b64decode(enc).decode("utf-8"))
# नमस्ते €
print(base64.urlsafe_b64encode(b"hi?>"))
# b'aGk_Pg=='
Call .decode("ascii") on the encoded bytes when you need a str for JSON. Encoding text this way works for any language, because UTF-8 turns it into bytes first.
Base64 in JavaScript
Browsers and Node.js have btoa() and atob(), but they only handle characters in the Latin-1 range:
btoa("Hello") // 'SGVsbG8='
atob("SGVsbG8=") // 'Hello'
btoa("नमस्ते") // InvalidCharacterError: Invalid character
For Unicode text in Node.js, use Buffer, which also supports base64url directly:
Buffer.from("नमस्ते").toString("base64") // '4KSo4KSu4KS44KWN4KSk4KWH'
Buffer.from("hi?>").toString("base64url") // 'aGk_Pg'
Note that Node’s base64url output dropped the padding. In browsers, convert text with TextEncoder to bytes first. Newer engines are adding Uint8Array.prototype.toBase64(), but our Node.js 24.22.1 did not have it yet, so check support before relying on it.
Decode errors and how to fix them
base64.b64decode("SGVsbG8")
# binascii.Error: Incorrect padding
s = "SGVsbG8"
base64.b64decode(s + "=" * (-len(s) % 4))
# b'Hello'
Missing padding is the most common error, usually from a URL-safe source that stripped it. Python also silently ignores characters outside the alphabet by default. Whitespace and newlines are skipped, which helps with wrapped email text, but junk is skipped too. Pass validate=True for strict checking:
base64.b64decode("SGVs*bG8=", validate=True)
# binascii.Error: Only base64 data is allowed
Use strict mode when decoding input from users or other systems, so corrupt data fails loudly instead of decoding into garbage.
Base64 is not encryption
This needs saying plainly. HTTP Basic authentication sends user:password as base64. We encoded a dummy pair:
base64.b64encode(b"demo:not-a-real-password")
# b'ZGVtbzpub3QtYS1yZWFsLXBhc3N3b3Jk'
base64.b64decode(b"ZGVtbzpub3QtYS1yZWFsLXBhc3N3b3Jk")
# b'demo:not-a-real-password'
One function call reverses it, with no key. Base64 hides nothing. Only HTTPS protects Basic auth credentials in transit. Never use base64 to “hide” secrets in config files, URLs or front-end code, and never trust a base64 value just because it looks scrambled.
Where you meet base64
- Data URIs:
data:image/png;base64,...for small inline images and fonts. - Email attachments via MIME.
- JWTs and OAuth tokens, using base64url.
- HTTP Basic auth headers.
- APIs that send files or signatures inside JSON.
- Kubernetes secrets, which store values base64 encoded, again not encrypted.
- PEM files for TLS certificates and SSH keys, which wrap base64 between header lines.
When you test an API that returns base64, do not just check that the field is present. Decode it in the test and compare the bytes with the expected file or value, and include a case whose length is not a multiple of three so the padding path runs. Those two checks catch most encoding bugs before users see broken images or corrupt downloads.
Base64 vs hex, base32 and base85
Base64 is not the only binary-to-text encoding. Each trades size against readability and character safety. We encoded the same 30 random-looking bytes, and the word “Hi!”, with each one using Python’s base64 module:
| Encoding | Characters for 30 bytes | “Hi!” becomes | Typical use |
|---|---|---|---|
| Hex (base16) | 60 | 486921 |
Hashes, debugging, colour codes |
| Base32 | 48 | JBUSC=== |
Case-insensitive codes, such as two-factor secrets |
| Base64 | 40 | SGkh |
General purpose, web and email |
| Base85 | 38 | NNFJ |
PDF and Git binary patches |
Hex doubles the size but is easy to read byte by byte. Base32 avoids lowercase letters and confusing symbols, so people can type it. Base85 is the most compact but uses many punctuation characters that are unsafe in URLs and JSON. Base64 sits in the sweet spot, which is why it became the default.
Base64 on the command line
Most systems include a base64 tool. In Git Bash we ran:
echo -n "Hello" | base64 # SGVsbG8=
echo "SGVsbG8=" | base64 -d # Hello
Use -n with echo, or the newline gets encoded too and the result changes. On macOS the decode flag is -D on older versions. In PowerShell, use [Convert]::ToBase64String() and [Convert]::FromBase64String() with bytes from [Text.Encoding]::UTF8.GetBytes(). Our Linux commands guide covers more terminal basics.
Final thoughts
Base64 encoding is a simple trick with wide reach: 3 bytes in, 4 safe characters out. Remember that it adds a third to the size, that = pads the last block, that URLs need the URL-safe variant, and that it offers no secrecy. In Python, work in bytes and decode strictly. In JavaScript, avoid btoa for Unicode. With those rules, those mysterious eyJ and SGVs strings stop being mysterious.
FAQ
What is base64 encoding used for?
It carries binary data through text-only channels such as JSON, email, URLs and HTTP headers, for example images in data URIs or tokens in JWTs.
Why does base64 end with an equals sign?
The equals sign is padding. When the input length is not a multiple of three bytes, one or two equals signs fill the final four character block.
How much bigger is base64 than the original?
About 33 percent bigger, because every three bytes become four characters. Our one million byte test produced 1,333,336 characters.
What is the difference between base64 and base64url?
Base64url replaces plus with a hyphen and slash with an underscore, and often drops padding, so the output is safe in URLs and file names.
Is base64 secure for passwords?
No. Base64 is reversible by anyone with no key. Use HTTPS to protect data in transit and proper hashing or encryption for secrets.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.