• Encoding
  • Security
  • JavaScript

Base64 is not encryption: what it's actually for

Base64 makes bytes safe for text-only channels. It hides nothing. How the encoding works, what it costs, and the bugs it causes when misused.

The utilyx team9 min read
On this page

You're reviewing a pull request and a config file contains this line:

yaml
db_password: cGFzc3dvcmQxMjM=

The author's note says it's fine because the value is encoded. Run it through any decoder and the argument ends:

bash
$ echo -n 'cGFzc3dvcmQxMjM=' | base64 -d
password123

Base64 has no key, no secret and no state. Anyone who recognizes the alphabet (and the trailing = gives it away) can reverse it in one command. That isn't a flaw. Base64 was never meant to hide anything. It solves a different, narrower problem, and most base64 bugs come from forgetting what that problem was.

What base64 is for

Lots of channels carry text but not arbitrary bytes. Early email was 7-bit. JSON strings must be valid Unicode. HTTP headers, XML attributes, URLs, environment variables and terminal copy-paste all choke on a null byte or a stray 0xFF. If you want to send a PNG, a signature or an encryption key through one of those channels, you need a way to spell bytes using only characters that survive the trip.

RFC 4648 §4 states the goal directly: base64 is designed to represent arbitrary sequences of octets in a form that allows the use of both upper- and lowercase letters but that need not be human readable. It picks 64 characters that are safe almost everywhere (A–Z, a–z, 0–9, +, /) plus = for padding, and maps every possible byte sequence onto them.

That's the whole job: transport safety. Confidentiality is a separate property, and base64 doesn't provide it.

How 3 bytes become 4 characters

64 is 2⁶, so each base64 character carries exactly 6 bits. Three bytes are 24 bits, which divide evenly into four 6-bit groups. The encoder works through the input three bytes at a time. Here is the text Man:

text
text      M         a         n
bytes     0x4D      0x61      0x6E
bits      01001101  01100001  01101110

regroup   010011  010110  000101  101110
value     19      22      5       46
char      T       W       F       u

Value 0–25 maps to A–Z, 26–51 to a–z, 52–61 to 0–9, then 62 is + and 63 is /. So 19 is T, 22 is W, 5 is F, 46 is u, and Man encodes to TWFu.

When the input doesn't divide by three

If one or two bytes are left over, the encoder pads the bits with zeros to finish the last 6-bit group, then writes = for each character position that carries no input at all:

text
"Ma"  01001101 01100001 + 00        → 010011 010110 000100     → TWE=
"M"   01001101 + 0000                → 010011 010000            → TQ==

Padding tells the decoder how many bytes the last group really holds, so the output is always a multiple of four characters. RFC 4648 §3.2 requires it unless the spec using base64 says otherwise. Some do, as we'll see.

The 33% tax, and what padding costs

Four output characters for every three input bytes means the encoded length is 4 × ceil(n / 3). For large inputs that's a flat 33.3% overhead; for tiny inputs padding makes it worse. We checked the formula with Buffer.alloc(n).toString("base64").length in Node 26:

Input bytesBase64 charsOverhead
14+300%
34+33%
48+100%
1,0001,336+33.6%
1,048,576 (1 MiB)1,398,104+33.3%
1 MiB, MIME-wrapped (76 chars + CRLF)1,434,896+36.8%

The last row matters for email and some legacy APIs: line breaks add another 2 bytes per 76 characters.

HTTP compression wins back much of that, because base64 output only uses 64 symbols and compressors exploit the slack. We measured it on the 64,794-byte PNG we use as our default social image: base64 grows it to 86,392 bytes, and gzip at level 9 brings that back to 59,170. That's less than the raw file, but gzipping the raw PNG gives 55,156, so encoding still costs you about 7% on the wire, plus the CPU to encode and decode.

base64 vs base64url

Two of the standard alphabet's characters are special in URLs. + means a space in form-encoded query strings, and / separates path segments. RFC 4648 §5 defines a "URL and filename safe" alphabet that swaps them for - and _. Everything else is identical.

js
const bytes = Buffer.from([0xfb, 0xff, 0xbf]);
bytes.toString("base64");    // "+/+/"
bytes.toString("base64url"); // "-_-_"

Send standard base64 through a query string and it breaks quietly. The + characters turn into spaces, and Node's decoder skips the characters it doesn't recognize instead of throwing:

js
const token = new URLSearchParams("token=+/+/").get("token");
// " / /"
Buffer.from(token, "base64");
// <Buffer ff>   (three bytes went in, one came out, no error)

JWTs are the most common base64url you'll meet. RFC 7515 (JWS) uses base64url with the padding removed, which is why a JWT header such as eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9 has no trailing =. Strict decoders want the padding back. Python's base64.b64decode("eyJhIjoxfQ") fails with binascii.Error: Incorrect padding; append = until the length is a multiple of four. We cover reading tokens in How to decode a JWT without pasting it into a stranger's website.

Encoding is not a lock

The opening example is the mild version. These are the places where treating base64 as protection causes real exposure.

Kubernetes Secrets

The data field of a Secret holds base64 values, which makes a manifest look scrambled. It isn't. The Kubernetes documentation says so up front:

The base64 is there so a Secret can hold binary data such as keystores, not to hide it. Committing a Secret manifest to Git is committing the password. Turn on encryption at rest for etcd, keep RBAC on Secrets tight, and keep the real values in a secret manager or encrypt them before they go into the repo.

Basic auth headers

RFC 7617 builds the header by joining user ID and password with a colon and base64-encoding the result. Its own example:

bash
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==

$ echo -n 'QWxhZGRpbjpvcGVuIHNlc2FtZQ==' | base64 -d
Aladdin:open sesame

The RFC's security considerations open with "The Basic authentication scheme is not a secure method of user authentication". Without TLS the password travels in plain text. With TLS it still lands in plain text in any proxy, log line or HAR file that records request headers. Redact the header before you share a log.

The trailing newline you encoded by accident

Not a leak, but it costs hours. echo appends a newline, and base64 encodes it:

bash
$ echo "hunter2" | base64
aHVudGVyMgo=
$ echo -n "hunter2" | base64
aHVudGVyMg==

The first value decodes to hunter2\n, and the database rejects it as a wrong password. If a secret works when you type it but not from a Secret, check for that Cg or go= at the end.

btoa and Unicode

The browser's btoa predates UTF-8 being universal. It takes a string where each character must be a single byte (Latin-1, code points 0–255). Anything above that throws:

js
btoa("café ✓");
// Node 26:  InvalidCharacterError: Invalid character
// Chrome:   Failed to execute 'btoa' on 'Window': The string to be encoded
//           contains characters outside of the Latin1 range.

The error is the better outcome. The worse one is input with only Latin-1 accents, because btoa accepts it and encodes the wrong bytes:

js
btoa("naïve");                            // "bmHvdmU="  (Latin-1 bytes)
Buffer.from("naïve").toString("base64");  // "bmHDr3Zl"  (UTF-8 bytes)

Buffer.from("bmHvdmU=", "base64").toString(); // "na�ve"

A server that decodes as UTF-8, which is nearly all of them, gets a replacement character. The mirror bug happens on the way back: atob("Y2Fmw6kg4pyT") returns café â followed by two invisible control characters, because atob hands you raw bytes dressed up as a string.

The fix is to be explicit about the step base64 doesn't cover: turning text into bytes. Use TextEncoder and TextDecoder:

js
function encodeBase64(text) {
  const bytes = new TextEncoder().encode(text);
  let binary = "";
  for (const b of bytes) binary += String.fromCharCode(b);
  return btoa(binary);
}

function decodeBase64(b64) {
  const bytes = Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
  return new TextDecoder().decode(bytes);
}

encodeBase64("café ✓");       // "Y2Fmw6kg4pyT"
decodeBase64("Y2Fmw6kg4pyT"); // "café ✓"

The loop is deliberate. The popular one-liner String.fromCharCode(...bytes) spreads every byte into a function argument and fails on large inputs; on a 1 MiB array Node throws RangeError: Maximum call stack size exceeded.

Newer runtimes ship a direct API, Uint8Array.prototype.toBase64() and Uint8Array.fromBase64(), with an alphabet: "base64url" option. They work in Node 26, which we used for every example here. Check browser support for your audience before you depend on them in front-end code. In Node, Buffer.from(text).toString("base64") has always been UTF-8 by default.

Line wrapping and lenient decoders

RFC 4648 §3.1 says implementations must not add line feeds unless the referring spec asks for them. Two common ones do: MIME limits lines to 76 characters and PEM to 64. Command-line tools often follow them by default, so the same value comes out differently depending on what produced it:

  • base64 (GNU coreutils and uutils) wraps at 76 columns. Use base64 -w 0 for one line.
  • openssl base64 wraps at 64. Use openssl base64 -A.
  • Python's base64.encodebytes wraps at 76 and adds a trailing \n; b64encode doesn't wrap.

Paste a wrapped value into a single-line field such as an environment variable or a YAML scalar, and what happens next depends entirely on the decoder:

DecoderReal newlines (CRLF)Literal \n (backslash + n)
atob (WHATWG forgiving decode)IgnoredInvalidCharacterError
Buffer.from(s, "base64")IgnoredSilently wrong: 100 bytes in, 101 out
base64.b64decode(s) (Python)DiscardedSilently wrong: 101 bytes out
b64decode(s, validate=True)Only base64 data is allowedSame error
Base64.getDecoder() (Java)Illegal base64 character dIllegal base64 character 5c
Base64.getMimeDecoder() (Java)IgnoredSilently wrong

The Java message names the offending byte in hex: d is a carriage return, 5c a backslash. The silently wrong rows are the dangerous ones. Lenient decoders drop the backslash but keep the n, because n is a valid base64 character, and every byte after it shifts. A literal \n from a badly escaped JSON or .env file therefore produces bytes that are subtly corrupt with no error at all. When the decoded value is a key or certificate, the failure surfaces much later and far away. Strip whitespace on purpose before decoding, and decode strictly when the input comes from outside.

Data URIs: when inlining helps and when it hurts

A data URI puts the bytes of a file into the URL itself: data:image/png;base64,iVBORw0KGgo…. It saves a request, which is real value for a tiny icon in a stylesheet, a favicon in a single-file HTML report, or an image in an email.

The costs grow with the file:

  • No separate caching. The image is re-downloaded every time the HTML or CSS that contains it changes, and can't be shared between pages.
  • It blocks rendering. An image inlined in CSS makes the stylesheet bigger, and the browser won't paint until it has the whole stylesheet. A normal image would have loaded in parallel.
  • The 33% tax, partly recovered. As measured above, compression gets most of it back but not all.
  • No lazy loading or responsive variants through srcset.

Our rule of thumb: inline assets of a few kilobytes that every page needs, and serve everything else as a file with a long cache lifetime. Measure with your own pages before you take anyone's threshold as gospel, including ours.

Base64 earns its place when bytes have to travel through a channel built for text. When someone uses it to hide a value, the value isn't hidden. To protect data, encrypt it with a real key. Then, if the ciphertext has to fit in a text field, base64 is the right way to carry it.

Try it: the utilyx Base64 encoder encodes text as UTF-8, switches between standard, URL-safe, MIME and PEM output, takes files and data URIs, and shows a hex dump of what it decoded. It runs in your browser, so a secret you're checking doesn't go anywhere, though if it's in a config file, it's already less secret than you think.

Try the Base64 encoder
Free, no sign-up, and it runs in your browser.
Open the tool →