Base64 explained: what it is, how it works, when to use it
You have seen Base64 even if you never asked for it: the eyJ… at the start of a JWT, the data:image/png;base64,… in a stylesheet, the wall of letters inside a raw email attachment. It is one of the most common encodings in software and one of the most misunderstood. This guide explains what problem it solves, walks through exactly how three bytes become four characters, and covers the variants and traps you will meet in real code.
Why Base64 exists
Computers store everything as bytes, and a byte can have any of 256 values. Many channels, though, were built to carry text: email (originally 7-bit ASCII only), JSON and XML documents, URLs, HTTP headers, HTML attributes. Push raw binary through them — an image, a PDF, a cryptographic signature — and some byte values get altered, stripped or treated as control characters, and the file arrives corrupted.
Base64 solves this by describing any bytes using only 64 characters that survive practically everywhere: A–Z, a–z, 0–9, + and /, plus = for padding. It is a representation, not protection: anyone can decode it, and no key is involved.
How it works: 3 bytes become 4 characters
64 = 2⁶, so each Base64 character carries exactly 6 bits. Three bytes are 24 bits, which divide evenly into four 6-bit groups. The encoder therefore reads the input three bytes at a time and writes four characters for each group. Let’s encode the word Man by hand:
Text: M a n
ASCII: 77 97 110
Bits: 01001101 01100001 01101110
Regroup the 24 bits into 6-bit chunks:
010011 010110 000101 101110
Values: 19 22 5 46
Alphabet: T W F u
Result: TWFu
The alphabet is just an index: 0–25 are A–Z, 26–51 are a–z, 52–61 are 0–9, 62 is + and 63 is /. So 19 is T and 46 is u. Decoding simply runs the steps backwards.
Padding: what the = signs mean
Input rarely comes in perfect multiples of three bytes. When one or two bytes are left over, the encoder fills the missing bits with zeros and adds = so that the output length is still a multiple of four:
| Input | Bytes | Base64 | Why |
|---|---|---|---|
Man | 3 | TWFu | Full group, no padding |
Ma | 2 | TWE= | 16 bits → 3 characters + one = |
M | 1 | TQ== | 8 bits → 2 characters + two == |
Padding carries no data. Because the original length can be worked out from the number of characters, many formats (JWTs among them) omit it, and good decoders accept both forms.
The size cost: about 33% bigger
Every 3 bytes turn into 4 characters, so encoded data is 4/3 the original size — roughly 33% more, plus up to two padding characters. A 1,000-byte file becomes 1,336 characters; a 3 MB photo becomes about 4 MB. Email encoders also insert a line break every 76 characters, adding a little more. That overhead is why Base64 suits small payloads, not bulk file transfer: if you can send binary directly (a normal HTTP upload with multipart/form-data, for example), do that.
URL-safe Base64
Two characters of the standard alphabet cause trouble in URLs and file names: + (often read as a space in query strings) and / (a path separator). The URL-safe variant from RFC 4648 swaps them for - and _, and usually drops the = padding as well, because = is also meaningful in query strings.
bytes FB FF BF standard: +/+/ URL-safe: -_-_
This is the variant JWTs use for all three parts. If a Base64 string contains - or _, decode it as URL-safe.
Data URIs
A data URI puts a whole file inside a URL, so the browser needs no extra request:
data:text/plain;base64,SGVsbG8sIERoYWthIQ==
<img src="data:image/png;base64,iVBORw0KGgo…" alt="icon">
That first one decodes to Hello, Dhaka!. Data URIs are handy for tiny icons and for single-file HTML reports, but because the data is 33% larger and cannot be cached separately from the page, large images are better served as normal files.
The UTF-8 trap in JavaScript
The browser functions btoa() and atob() date from a time when strings were assumed to be Latin-1. They work on characters with codes 0–255 only, so anything outside that range fails:
btoa('বাংলা'); // InvalidCharacterError: Invalid character
Base64 encodes bytes, so first turn the text into UTF-8 bytes, then encode those bytes — and reverse both steps when decoding:
// Browser (and Node)
const bytes = new TextEncoder().encode('বাংলা'); // 15 UTF-8 bytes
const b64 = btoa(String.fromCharCode(...bytes)); // '4Kas4Ka+4KaC4Kay4Ka+'
const text = new TextDecoder().decode(
Uint8Array.from(atob(b64), (c) => c.charCodeAt(0))
); // 'বাংলা'
// Node.js
Buffer.from('বাংলা', 'utf8').toString('base64'); // '4Kas4Ka+4KaC4Kay4Ka+'
Buffer.from('4Kas4Ka+4KaC4Kay4Ka+', 'base64').toString('utf8');
Buffer.from(bytes).toString('base64url'); // URL-safe, no padding
If you skip TextDecoder and call atob() alone, you get 15 garbled Latin-1 characters instead of five Bangla letters — the classic “mojibake” bug. For very large inputs, encode in chunks, because spreading millions of bytes into String.fromCharCode can exceed the engine’s argument limit.
Python and the shell work on bytes explicitly:
import base64
base64.b64encode('বাংলা'.encode('utf-8')) # b'4Kas4Ka+4KaC4Kay4Ka+'
base64.urlsafe_b64encode(bytes([0xfb, 0xff, 0xbf])) # b'-_-_'
$ echo -n 'Hello, Dhaka!' | base64
SGVsbG8sIERoYWthIQ==
Watch the newline: without -n, echo adds a line break and you get SGVsbG8sIERoYWthIQo= — a different string that decodes with an extra newline at the end.
Where you will meet it
- JWTs: header, payload and signature are URL-safe Base64 without padding. That is why a token’s contents are readable by anyone — see how to decode a JWT.
- Email: MIME attachments and non-ASCII message bodies are sent with
Content-Transfer-Encoding: base64, split into 76-character lines. - HTTP Basic auth: the header
Authorization: Basic dXNlcjpwYXNzis justuser:passin Base64 — which is why Basic auth is only acceptable over HTTPS. - APIs and config: binary fields in JSON, certificates in PEM files, Kubernetes Secrets.
Base64 is not encryption. Encoding a password or API key in Base64 hides it from nobody. For the difference between encoding, encryption and hashing, read this guide.
FAQ
Why does my Base64 end with one or two = signs?
The input length was not a multiple of three bytes. One leftover byte produces ==, two leftover bytes produce =. They are padding only and carry no data.
Can I use Base64 to shrink data?
No — it always makes data about a third larger. If size matters, compress first (for example with gzip) and Base64-encode the compressed bytes only if the channel requires text.
Why do I get “Invalid character” when decoding?
Usually the string is URL-safe (contains - or _) and your decoder expects the standard alphabet, or it contains spaces, quotes or a data:…;base64, prefix that must be removed first.