Base64 is a binary-to-text encoding scheme that converts arbitrary binary data into a string of ASCII characters. It is used whenever there is a need to transfer binary data over a medium that only supports text.
How it works
Base64 works by taking three bytes of binary data (24 bits) and encoding them as four ASCII characters. Each character represents 6 bits of data, chosen from a 64-character alphabet:
- A-Z (26 characters)
- a-z (26 characters)
- 0-9 (10 characters)
- `+` and `/` (2 characters)
The encoded output is always a multiple of 4 characters. If the input is not a multiple of 3 bytes, = padding characters are added.
Common use cases
- **Email attachments**: MIME encoding uses Base64 to send binary files as text
- **Data URIs**: Embedding images directly in HTML or CSS as `data:image/png;base64,...`
- **JWTs**: JSON Web Tokens encode their header and payload using Base64url (a URL-safe variant)
- **Basic auth**: HTTP Basic Authentication encodes credentials as Base64
Base64 vs Base64url
Standard Base64 uses + and / which are not URL-safe. Base64url replaces these with - and _ and omits padding.
Performance
Base64 increases data size by approximately 33%. For every 3 bytes of input, 4 bytes of output are produced.
When not to use Base64
Base64 is an encoding scheme, not encryption. Do not use it to hide sensitive data. Use proper encryption algorithms for that purpose.