1. Application Scenarios
1.1 Mail
RFC821 requires that email content be ASCII. When a message contains other non-ASCII characters or binary data, Content-Transfer-Encoding is needed, and Base64 is one such method.
1.2 URL
Some applications need to put binary data into a URL, but URLs only allow a specific set of ASCII characters. This also calls for Base64 encoding. Of course, this only encodes the data itself; the encoded data may contain + and /, so when it is actually placed into a URL it still needs URL-Encoding to become the %XX form.
1.3 Embedding Images in HTML
This approach encodes an image as a Base64 string and places it in the HTML page. Once the HTML page has finished loading, the image data has loaded with it, with no separate HTTP request required.
The data: URI is defined in the IETF standard RFC 2397. The basic usage format is as follows:
| |
MIME-type is the MIME type of the embedded data, for example image/png for a PNG image. If base64 follows immediately, it means the data that follows is Base64-encoded.
1.4 Digital Certificate Signatures
CER, CRT, PEM, and KEY certificates are all in Base64-encoded format.
1.5 De-visualization
Base64 is not recommended for encryption, but some scenarios simply need to turn a plain string into an unrecognizable one β for example Cookie and Signature parameters. Some blogs also Base64-encode email addresses to avoid spam.
2. How Base64 Works
2.1 Base64 Encoding
Base64 encoding converts 3 8-bit bytes (38=24) into 4 6-bit bytes (46=24), then pads two 0s in front of each 6 bits to form 8-bit bytes. When the original data is not a multiple of 3, if two input bytes remain at the end, one “=” is appended to the encoded result; if one input byte remains, two “=” are appended; if nothing remains, nothing is appended.
2.2 Base64 Decoding
Decoding is the reverse of encoding: strip the trailing =, expand in 8-bit units, and if it is not a multiple of 8, pad 0 at the end, then convert to ASCII.
3. Frontend JavaScript Implementation
This mainly uses the library functions provided by the js-base64 project.
| |
4. Backend Python Implementation
| |
When handling Chinese, note that the Python base64 library is implemented according to RFC 3548 and can only handle Byte and ASCII characters. The solution is to first convert the Unicode characters into Bytes.
Processing flow: Unicode -> Byte string -> Base64 String -> Byte String -> Unicode
Because standard Base64 encoding may produce the characters + and /, which cannot be used directly as URL parameters, there is also a “url safe” Base64 encoding, which simply turns the characters + and / into - and _ respectively:
| |
