Base64 Explained
See how Base64 turns bytes into safe text, where you meet it, how to encode and decode it, and why it is not encryption.
Key takeaways
- Base64 turns every group of 3 bytes into 4 text characters.
- The
=sign pads the end when the input length isn't a multiple of three. - A URL-safe variant swaps
+and/for-and_. - Encoding offers no secrecy at all, so never treat a Base64 string as protected.
- Use it when a text channel requires it, and send raw bytes when the channel allows them.
Base64 is a way of writing any binary data using only 64 ordinary text characters, plus a padding sign. It lets you carry images, keys or other raw bytes through systems that expect text, such as email, JSON documents or HTTP headers.
It isn't encryption and it isn't compression. Anyone can reverse it without a key, and the result is about a third larger than the original.
Why text channels need help
Many older and some current systems were designed for text. Certain byte values have special meanings: they end a string, break a line or get altered in transit. Early email in particular was built around 7-bit ASCII.
Base64 sidesteps this by using a small alphabet that survives almost anywhere: A to Z, a to z, 0 to 9, + and /. The standard definition is RFC 4648.
How the encoding works
Three bytes are 24 bits. Split those 24 bits into four groups of 6. Six bits can hold a value from 0 to 63, and each value selects one character from the alphabet.
Take the word Man:
characters M a n
bytes 77 97 110
bits 01001101 01100001 01101110
6-bit groups 010011 010110 000101 101110
values 19 22 5 46
Base64 T W F u So Man encodes as TWFu. Values 0 to 25 map to uppercase letters, 26 to 51 to lowercase, 52 to 61 to digits, then + and /.
Padding
Input doesn't always divide into threes. When one byte is left over, the encoder produces two characters followed by ==. When two bytes are left over, it produces three characters and one =.
| Input | Base64 |
|---|---|
Man | TWFu |
Ma | TWE= |
M | TQ== |
Padding keeps the length a multiple of four. Some formats omit it because the length already tells the decoder what's missing. A strict decoder may reject unpadded input, so you may need to add the = signs back.
Size cost
Four characters for every three bytes means output about 33 percent larger. A 3 MB file becomes about 4 MB of text. MIME email also inserts line breaks, adding a little more. This is why an attachment takes up more space in a message than on disk.
Compression applied during transfer claws back some of the difference for certain data, but already-compressed files such as JPEG images stay noticeably larger. Decoding also costs memory and processing time, which matters for large files on small devices.
Where you meet it
A data URL looks like data:image/png;base64,iVBORw0KGgo.... It saves a separate request for a tiny graphic, but it can't be cached apart from the file containing it, so large embedded images usually hurt page speed.
In email and the wider mail system, MIME marks a part with Content-Transfer-Encoding: base64, and your mail program decodes it without showing you.
It isn't security
An encoded string looks scrambled, which tempts people to hide passwords or keys with it. Decoding takes one command and no secret.
HTTP Basic authentication is a good example. The header Authorization: Basic dXNlcjpwYXNz is just user:pass encoded. Its protection comes entirely from the HTTPS connection around it. Similarly, secrets in some deployment systems are shown Base64 encoded, which by itself protects nothing.
If you need confidentiality, use encryption. If you need to detect changes, use a hash or signature. The distinctions are laid out in hashing vs. encryption vs. encoding. Also be aware that malicious messages and scripts use encoding to make content less obvious, so an unexplained blob in an unexpected place is worth a careful look in a safe, text-only viewer.
The URL-safe variant
+, / and = all have meanings in web addresses or file names. RFC 4648 therefore defines a second alphabet that uses - instead of + and _ instead of /, often with padding removed. JSON Web Tokens use it.
The two aren't interchangeable. If a decoder complains about an illegal character, check which alphabet produced the string. If you put standard Base64 in a query string, it must be percent-encoded, or a + may arrive as a space; see URL encoding.
Encoding and decoding yourself
On Linux or macOS:
printf '%s' 'Man' | base64
echo 'TWFu' | base64 --decode printf is used because plain echo adds a newline that would be encoded too, which is the usual reason a result differs from what you expected.
In Windows PowerShell:
[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes('Man'))
[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('TWFu')) In a browser, btoa and atob work only with characters in the 0 to 255 range. For other text, convert to UTF-8 bytes first with TextEncoder, then encode.
For quick experiments, a Base64 converter handles text, and the image and Base64 converter handles pictures. Don't paste real credentials or private keys into any web page you don't control.
Decoding by hand
Working backward once makes the format easy to recognize. Take SGk=. Look up each character's value: S is 18, G is 6 and k is 36. The = is padding.
Write the three values as 6-bit groups: 010010, 000110, 100100. Joined, that's 18 bits. Cut them into bytes: 01001000 and 01101001, with two spare bits that are zero. Those bytes are 72 and 105, which in ASCII are H and i.
A few patterns become familiar with practice. JSON objects that begin {" encode to a string starting eyJ. PNG images start iVBORw0KGgo. JPEG files usually start /9j/. PDF files start JVBER. These prefixes help you guess what an unlabeled blob holds, though only decoding and inspecting it confirms the guess.
Files, certificates and keys
On Linux and macOS you can encode a whole file with base64 photo.png > photo.txt, though option names for line wrapping and input files differ between the two systems, so check the manual page. In Windows, certutil -encode and certutil -decode convert files from the command prompt, with -encode adding header and footer lines.
Those lines are the PEM convention. A certificate or key in a PEM file is binary data, Base64 encoded, wrapped between markers such as -----BEGIN CERTIFICATE----- and a matching end line. A certificate is public and meant to be shared. A block labeled as a private key is a secret, however unreadable it looks, and belongs only in protected storage.
After moving a file through a text channel, compare a checksum of the original and the decoded copy. Identical checksums show the bytes came through unchanged.
When to avoid it
If a channel handles binary data, use it. Uploading a file with a multipart form request or a direct binary body saves bandwidth and lets the server stream it to disk. Putting large files as Base64 inside JSON forces both sides to hold a bigger string in memory and to parse it before doing anything else.
In databases, a binary column type is usually better than Base64 in a text column. It takes less space, and nobody has to remember whether a given value was encoded.
Text encoding comes first
Base64 works on bytes, not on characters. Before encoding text you have to choose how that text becomes bytes. The word é encoded as UTF-8 and as an old single-byte code page gives two different Base64 strings. Agree on UTF-8, as explained in character encoding, and decoded text will come out right.
Relatives of Base64
RFC 4648 also describes Base32, which uses a smaller alphabet that doesn't depend on letter case and is handy for codes people type, and Base16, which is ordinary hexadecimal at two characters per byte. Base58 variants, used in some applications, drop characters that look alike. Each trades length against convenience.
Handling input from others
When your program accepts Base64 from outside, treat the decoded result as untrusted. Limit the encoded length before decoding, so an enormous upload can't exhaust memory. Verify that the decoded bytes are the kind of file you expect by inspecting their content, not just the type label the sender supplied. Decide whether you accept whitespace, missing padding or the URL-safe alphabet, and reject everything else with a clear error. Lenient decoders that silently skip odd characters can let two components read the same string differently, which is a source of subtle bugs.
Troubleshooting
- Invalid length: padding was stripped or the string was cut off while copying.
- Illegal character: wrong alphabet, a space where
+should be, or surrounding quotes included. - Output looks like noise: the original data was binary, or it was compressed or encrypted before encoding. Check the first bytes to identify the file type.
- Stray character at the end of text: a newline was encoded along with it.
- Encoded twice: decoding yields another Base64 string. Find where the extra step happens instead of decoding twice downstream.
Common questions
Can I tell whether a string is Base64?
You can only make a good guess. The alphabet and a length divisible by four are hints, but plenty of ordinary words pass that test. The surrounding format or documentation should say.
Does Base64 make a file safe to open?
No. Decoding returns exactly the original bytes, harmful or not.