Unpadded Base64
The `unpaddedbase64` library provides functionality to encode and decode Base64 strings that explicitly omit the '=' padding characters. While RFC 4648 specifies that Base64 should be padded to a multiple of 4 bytes, many protocols choose to leave out this padding. The current version is 2.1.0, released in March 2021, and the library has an infrequent release cadence.
Warnings
- gotcha Python's built-in `base64` module by default expects and sometimes requires '=' padding for decoding. Using `base64.b64decode()` with an unpadded string (which this library produces) will often result in a `binascii.Error: Incorrect padding`. This library is specifically designed to handle unpadded Base64.
- gotcha This library handles the *unpadded* aspect of Base64 but does not automatically implement the URL-safe Base64 alphabet. Standard Base64 uses `+` and `/`, which need percent-encoding in URLs. URL-safe Base64 (RFC 4648 §5) replaces these with `-` and `_`. If you require both unpadded and URL-safe encoding, you'll need to handle the character substitution yourself or use `base64.urlsafe_b64encode/decode` (and be mindful of its padding behavior).
Install
-
pip install unpaddedbase64
Imports
- unpaddedbase64
import unpaddedbase64
Quickstart
import unpaddedbase64
# Encode a byte string to unpadded Base64
data_bytes = b'\x00\x01\x02'
encoded_string = unpaddedbase64.encode_base64(data_bytes)
print(f"Encoded: {encoded_string}")
assert encoded_string == 'AAEC'
# Decode an unpadded Base64 string back to bytes
decoded_bytes = unpaddedbase64.decode_base64('AAEC')
print(f"Decoded: {decoded_bytes}")
assert decoded_bytes == data_bytes
# Example with a string that would typically have padding
long_data = b'This is a test string.'
encoded_long = unpaddedbase64.encode_base64(long_data)
print(f"Encoded long: {encoded_long}")
# assert encoded_long == 'VGhpcyBpcyBhIHRlc3Qgc3RyaW5nLg' (original would be 'VGhpcyBpcyBhIHRlc3Qgc3RyaW5nLg==')
decoded_long = unpaddedbase64.decode_base64(encoded_long)
print(f"Decoded long: {decoded_long}")
assert decoded_long == long_data