What Base64 is actually for
RFC 4648 says what base encoding is for: storing or transferring data “in environments that, perhaps for legacy reasons, are restricted to US-ASCII data”. The RFC adds that it is also used where there is no such limit, “simply because it makes it possible to manipulate objects with text editors”. It takes bytes a channel might mangle — an image, a key, a character outside ASCII — and writes them with 64 printable characters that almost nothing objects to.
Why the output is about a third longer
The ratio is fixed by the standard. “The encoding process represents 24-bit groups of input bits as output strings of 4 encoded characters” (RFC 4648, 4): three bytes in, four characters out. So roughly a third is added, every time, and padding with = rounds the last group up.
That is worth remembering before embedding an image in a page or a stylesheet as a data URI. The picture does not get smaller by being encoded; it gets about 33% bigger, and it can no longer be cached on its own.
There are two alphabets, and they are not interchangeable. The ordinary one uses + and /, which both have jobs of their own in a URL or a filename. For those places RFC 4648 (5) defines a URL and filename safe alphabet, “base64url”, and warns that it “should not be regarded as the same as the ‘base64’ encoding”. A token pasted from a URL is usually the second kind.
Good fit, poor fit
Worth doing: reading the inside of something already encoded — a data URI, a config value, part of a token; putting bytes somewhere that only accepts text; checking that a string really is valid Base64 before blaming something else.
Not for this: keeping anything secret. The alphabet is published in the RFC and every language has a decoder, so encoding is a formatting step and nothing more. If data needs protecting, it needs encryption, which is a different thing entirely.
Frequently asked questions
- and _, and says it “should not be regarded as the same as the ‘base64’ encoding”. Missing padding is the next suspect.