Base58
The `base58` library provides an implementation of Base58 and Base58Check encoding and decoding, compatible with schemes used by the Bitcoin network. It also supports custom alphabets, such as the XRP one. The current version is 2.1.1, and the library has a stable release history with periodic updates to address compatibility and features.
Warnings
- breaking Python 2 support was dropped in version 2.0.0. Projects still on Python 2 must use the 1.x series, which will not receive new features.
- gotcha Encoding and decoding functions (`b58encode`, `b58decode`, etc.) strictly expect bytes-like objects as input. Passing a plain Python string will result in errors or incorrect encoding.
- gotcha When decoding, the input string must strictly adhere to the Base58 character set. The library's decoding functions will raise a `ValueError` if invalid characters (e.g., '0', 'O', 'I', 'l' which are excluded from Base58) are present.
- gotcha If using custom alphabets (e.g., `base58.XRP_ALPHABET`), ensure that the *exact same alphabet* is used for both encoding and subsequent decoding. Mismatched alphabets will lead to `ValueError` or corrupted data.
- gotcha When dealing with Base58Check, the checksum calculation (typically a double SHA-256 hash) and its inclusion are crucial. Manually implementing this can be prone to errors in hashing or byte extraction.
Install
-
pip install base58
Imports
- b58encode
import base58 base58.b58encode(...)
- b58decode
import base58 base58.b58decode(...)
- b58encode_check
import base58 base58.b58encode_check(...)
- b58decode_check
import base58 base58.b58decode_check(...)
- XRP_ALPHABET
import base58 base58.XRP_ALPHABET
Quickstart
import base58
# Encode binary data
data_bytes = b'hello world'
encoded_data = base58.b58encode(data_bytes)
print(f"Encoded: {encoded_data.decode('ascii')}")
# Decode Base58 string back to bytes
decoded_bytes = base58.b58decode(encoded_data)
print(f"Decoded: {decoded_bytes.decode('utf-8')}")
# Encode with Base58Check (includes a checksum)
data_for_check = b'my secret data'
encoded_check = base58.b58encode_check(data_for_check)
print(f"Encoded (with check): {encoded_check.decode('ascii')}")
# Decode Base58Check (verifies checksum)
decoded_check = base58.b58decode_check(encoded_check)
print(f"Decoded (with check): {decoded_check.decode('utf-8')}")
# Using a custom alphabet (e.g., XRP/Ripple)
xrp_data = b'xrp address seed'
encoded_xrp = base58.b58encode(xrp_data, alphabet=base58.XRP_ALPHABET)
print(f"Encoded (XRP alphabet): {encoded_xrp.decode('ascii')}")