hbutils.encoding.base64
- Overview:
Base64 encode and decode utilities.
This module provides convenient wrapper functions for base64 encoding and decoding operations, supporting both standard and URL-safe base64 formats. It simplifies the usage of Python’s built-in base64 module by providing a cleaner interface with optional URL-safe mode.
base64_encode
- hbutils.encoding.base64.base64_encode(data: bytes, altchars: bytes | None = None, urlsafe: bool = False) str[source]
Encoding the given binary data to base64 string.
This function encodes binary data into a base64-encoded string. It supports both standard base64 encoding and URL-safe base64 encoding. When URL-safe mode is enabled, the characters ‘+’ and ‘/’ in standard base64 are replaced with ‘-’ and ‘_’ respectively.
- Parameters:
data (bytes) – Binary data to be encoded.
altchars (Optional[bytes]) – Characters to be altered in standard base64 encoding. This parameter is ignored when urlsafe is True. Default is
None.urlsafe (bool) – Enable URL-safe mode. When True, uses URL-safe base64 encoding which replaces ‘+’ with ‘-’ and ‘/’ with ‘_’. Default is
False.
- Returns:
Base64-encoded string representation of the input data.
- Return type:
str
- Raises:
UserWarning – When both urlsafe is True and altchars is provided, a warning is issued indicating that altchars will be ignored.
Examples:
>>> base64_encode(b'jvMIQ?K;]kNn2?1KD5H>') 'anZNSVE/Sztda05uMj8xS0Q1SD4=' >>> base64_encode(b'jvMIQ?K;]kNn2?1KD5H>', urlsafe=True) 'anZNSVE_Sztda05uMj8xS0Q1SD4='
base64_decode
- hbutils.encoding.base64.base64_decode(base64_str: str, altchars: bytes | None = None, urlsafe: bool = False) bytes[source]
Decode the given base64 string back to binary data.
This function decodes a base64-encoded string back into its original binary form. It supports both standard base64 decoding and URL-safe base64 decoding. When URL-safe mode is enabled, it properly handles the URL-safe characters ‘-’ and ‘_’ used in place of ‘+’ and ‘/’.
- Parameters:
base64_str (str) – Base64-encoded string to be decoded.
altchars (Optional[bytes]) – Characters to be altered in standard base64 decoding. This parameter is ignored when urlsafe is True. Default is
None.urlsafe (bool) – Enable URL-safe mode. When True, uses URL-safe base64 decoding which handles ‘-’ and ‘_’ characters. Default is
False.
- Returns:
Decoded binary data from the base64 string.
- Return type:
bytes
- Raises:
UserWarning – When both urlsafe is True and altchars is provided, a warning is issued indicating that altchars will be ignored.
Examples:
>>> base64_decode('anZNSVE/Sztda05uMj8xS0Q1SD4=') b'jvMIQ?K;]kNn2?1KD5H>' >>> base64_decode('anZNSVE_Sztda05uMj8xS0Q1SD4=', urlsafe=True) b'jvMIQ?K;]kNn2?1KD5H>'