Base64 Encoding Explained: How It Works and When to Use It

Published

Base64 lets binary data, or text in any character set, travel through systems that only handle plain ASCII text. You meet it in email attachments, data URIs, JSON Web Tokens and API payloads. This guide explains how it works and when to use it.

How Base64 works

Base64 (defined in RFC 4648) takes the input bytes three at a time, splits those 24 bits into four groups of 6 bits, and maps each 6-bit value (0 to 63) to a character from this alphabet: A–Z, a–z, 0–9, + and /.

Text:    Hi!
Bytes:   72       105      33
Bits:    01001000 01101001 00100001
6-bit:   010010 000110 100100 100001
Index:   18     6      36     33
Base64:  S      G      k      h      ->  SGkh

Padding and size

When the input length is not a multiple of three, the last group is padded and = characters fill the output to a multiple of four: Hi becomes SGk= and H becomes SA==.

Because every 3 bytes become 4 characters, Base64 output is about 33% larger than the input, plus padding. That overhead is why large files are better sent as binary.

Text and UTF-8

Base64 encodes bytes, not characters. Text must first be turned into bytes, almost always as UTF-8. The browser's btoa function only accepts characters in the Latin-1 range, so encoding "café" or emoji directly fails. Convert Ferry's encoders convert text to UTF-8 first, and decode back from UTF-8.

The URL-safe variant

+ and / have special meanings in URLs, so RFC 4648 also defines base64url, which uses - and _ instead and usually drops the padding. JSON Web Tokens use base64url. Convert Ferry's decoders accept both alphabets.

Where Base64 is used

  • Data URIs: data:image/png;base64,iVBOR... embeds a small image in HTML or CSS. Decode one with Base64 to Image.
  • Email attachments (MIME).
  • Tokens: the header and payload of a JWT are base64url-encoded JSON.
  • APIs that need to carry binary data inside JSON.
  • HTTP Basic authentication headers.

Base64 is not encryption

Anyone can decode Base64 instantly. It hides nothing. A Base64-encoded password in a configuration file or a Basic Auth header is effectively plain text, which is why Basic Auth must only be used over HTTPS. Use real encryption, and a secrets manager, for anything sensitive.

Encoding and decoding structured data

The JSON to Base64, XML to Base64 and YAML to Base64 encoders check that your data is valid before encoding it, and the matching decoders pretty-print or validate the decoded result, so a corrupt payload is caught immediately.

Frequently asked questions

Why does my Base64 end with = or ==?

That is padding, added when the input length is not a multiple of three bytes.

Can Base64 contain line breaks?

Some systems, such as MIME email, wrap Base64 at 76 characters. Convert Ferry ignores whitespace when decoding.

Is Base64 compression?

No. It makes data larger, by about a third.

Related guides