What is Base64 and what is it for?
Base64 is an encoding that turns binary data, such as an image or a file, into plain text made of letters, digits and a few symbols. You run into it in emails, JWTs and web addresses.
Why is it needed?
Some systems can only carry plain text. Email used to carry only text, and JSON and URLs cannot carry raw bytes safely either. Base64 gets around this by writing any data with 64 safe characters (A-Z, a-z, 0-9, + and /).
How does it work?
The data is grouped three bytes at a time (24 bits) and those 24 bits are split into four pieces of six bits. Each piece maps to a letter from a 64-character table. So every 3 bytes become 4 characters.
That is why Base64 makes data about 33% larger. For example a 1,000,000 byte file becomes 1,333,336 characters of Base64 text. The = signs at the end are padding that completes the data when it is not a multiple of 3.
Base64 is not encryption
Keep this in mind: Base64 is an encoding, not encryption. It needs no key and anyone can reverse it. Saying "I Base64-ed this data so it is safe" is wrong. In basic authentication the username and password are sent as Base64, but that does not protect them, HTTPS does.
Where is it used?
- Email attachments (MIME) and some file formats.
- Embedding small images straight into HTML or CSS (data URLs).
- Tokens such as JWTs (in the Base64url form).
- Carrying binary data inside JSON.
Base64url: the variant for addresses
The + and / characters of standard Base64 cause trouble in web addresses. Base64url uses - and _ instead and drops the trailing = padding. The Base64 converter supports both.
Watch out with accented characters
When turning text into Base64, it matters which encoding the text is converted to bytes with. On the web the standard is UTF-8. JavaScript's btoa function throws an error for characters outside Latin-1, so text must be converted to UTF-8 bytes first. Our tools do this automatically, so letters like ş and é and emoji work fine.
Do not use Base64 to hide secret data. If you need secrecy, use real encryption.