Developer

Base64 encoding

An encoding that writes binary data as 64 printable ASCII characters. It's used to embed binary data in JSON, URLs, and email, and it adds about 33% to the size.

Three bytes in, four characters out

Base64 reads the input 3 bytes (24 bits) at a time and cuts those bits into four groups of 6 bits. Each group is a number from 0 to 63 that picks one character from A-Z, a-z, 0-9, + and /. The three bytes of Man become TWFu.

When the input isn't a multiple of three bytes, = pads the end. One leftover byte gives two characters plus ==, and two leftover bytes give three characters plus =. So a single byte still takes 4 characters, and the output length is always a multiple of four.

What the encoding costs

Four characters for every three bytes makes the text one-third longer than the data, about 33% extra. Here's how that looks for real data:

  • A SHA-256 hash is 32 bytes. In Base64 it's 44 characters, against 64 in hex.
  • A 30,000-byte image inlined as a data URI becomes 40,000 characters of text, before the data: prefix.

For large payloads, hex runs 1.5 times as long as Base64. That cost is why big files usually travel as binary and not as Base64 inside JSON. Use Base64 when the channel only carries text: JSON, XML, email and data URIs.

Encoding, not encryption

Anyone can reverse Base64 with no key. RFC 4648 is blunt about it: base encoding hides data from a glance but gives no computational confidentiality. A JWT's header and payload are Base64url text, so anyone who holds the token can read its claims. The signature only proves they weren't changed. Never use Base64 to protect a password or a key.

URL safe and other variants

Standard Base64 uses + and /, which mean something in URLs. Base64url (RFC 4648 section 5) swaps them for - and _, and the padding is often dropped. JWT segments use it, so a 32-byte value takes 43 characters there, against 44 with padding.

In a browser, btoa() only accepts characters with a code below 256, so text like ✓ throws an error. Turn the text into UTF-8 bytes first, then encode the bytes. Base32 is another variant: it trades size for an alphabet that's easier to type and read aloud.

Work it out yourselfOpen the Text Encoding Converter

Sources

Back to the glossary