Class Base58
- All Implemented Interfaces:
BinaryDecoder,BinaryEncoder,Decoder,Encoder
Base58 is a binary-to-text encoding scheme that uses a 58-character alphabet to encode data. It avoids characters that can be confused (0/O, I/l, +/) and is commonly used in Bitcoin and other blockchain systems.
Encoding and decoding produce results when EOF is signaled.
Decoding rejects input longer than a configurable maximum (DEFAULT_MAX_DECODE_LENGTH encoded bytes by default, see
Base58.Builder.setMaxDecodeLength(int)). Encoding rejects binary input longer than DEFAULT_MAX_ENCODE_LENGTH bytes by default; configure it with
Base58.Builder.setMaxEncodeLength(int). These limits apply to the total input across all chunks in an operation. Memory usage is proportional to the
accumulated input and conversion output. Encoded output can exceed the decode limit; configure both limits appropriately for larger trusted values.
This class is thread-safe for read operations but the Context object used during encoding/decoding should not be shared between threads.
The Base58 alphabet is:
123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz
This excludes: 0, I, O, and l.
- Since:
- 1.22.0
- See Also:
-
Nested Class Summary
Nested ClassesNested classes/interfaces inherited from class org.apache.commons.codec.binary.BaseNCodec
BaseNCodec.AbstractBuilder<T,B extends BaseNCodec.AbstractBuilder<T, B>>, BaseNCodec.Context -
Field Summary
FieldsModifier and TypeFieldDescriptionprivate static final BigIntegerprivate static final byte[]This array is a lookup table that translates Unicode characters drawn from the "Base58 Alphabet" into their numeric equivalents (0-57).private static final intstatic final intThe default maximum number of encoded bytes accepted by a single decode operation: 8192.static final intThe default maximum number of binary bytes accepted by a single encode operation: 8192.private static final byte[]Base58 alphabet: 123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz (excludes: 0, I, O, l).private static final intprivate final intThe maximum number of encoded bytes accepted by a single decode operation.private final intThe maximum number of binary bytes accepted by a single encode operation.Fields inherited from class org.apache.commons.codec.binary.BaseNCodec
CHUNK_SEPARATOR, decodeTable, DECODING_POLICY_DEFAULT, EMPTY_BYTE_ARRAY, encodeTable, EOF, lineLength, MASK_8BITS, MIME_CHUNK_SIZE, pad, PAD, PAD_DEFAULT, PEM_CHUNK_SIZE -
Constructor Summary
ConstructorsConstructorDescriptionBase58()Constructs a Base58 codec used for encoding and decoding.Base58(Base58.Builder builder) Constructs a Base58 codec used for encoding and decoding with custom configuration. -
Method Summary
Modifier and TypeMethodDescriptionstatic Base58.Builderbuilder()Creates a new Builder.private static byte[]calculateDecodeTable(byte[] encodeTable) Calculates a decode table for a given encode table.private voidcheckLength(int length, int accumulatedLength, int maximum, String operation) private voidcode(byte[] array, int offset, int length, BaseNCodec.Context context, int maximum, String operation, BiConsumer<byte[], BaseNCodec.Context> consumer) private voidconvertFromBase58(byte[] base58, BaseNCodec.Context context) Converts Base58 encoded data to binary.private byte[]convertToBase58(byte[] accumulate, BaseNCodec.Context context) Converts accumulated binary data to Base58 encoding.(package private) voiddecode(byte[] array, int offset, int length, BaseNCodec.Context context) Decodes the given Base58 encoded data.(package private) voidencode(byte[] array, int offset, int length, BaseNCodec.Context context) Encodes the given binary data as Base58.longgetEncodedLength(byte[] array) Gets the number of Base58 characters needed to encode the supplied array.private StringBuildergetStringBuilder(byte[] accumulate) Gets the Base58 string representation of the given binary data.protected booleanisInAlphabet(byte value) Tests whether theoctetis in the Base58 alphabet.private static byte[]toDecodeTable(byte[] encodeTable) Gets the decode table that matches the given encode table.Methods inherited from class org.apache.commons.codec.binary.BaseNCodec
available, code, containsAlphabetOrPad, decode, decode, decode, encode, encode, encode, encodeAsString, encodeToString, ensureBufferSize, getChunkSeparator, getCodecPolicy, getDefaultBufferSize, hasData, isInAlphabet, isInAlphabet, isStrictDecoding, isWhiteSpace, readResults, toUnsignedBytes, validateCanonicalByte, validateCanonicalEnd
-
Field Details
-
BASE
-
DECODING_TABLE_LENGTH
private static final int DECODING_TABLE_LENGTH- See Also:
-
ENCODING_TABLE_LENGTH
private static final int ENCODING_TABLE_LENGTH- See Also:
-
DEFAULT_MAX_DECODE_LENGTH
public static final int DEFAULT_MAX_DECODE_LENGTHThe default maximum number of encoded bytes accepted by a single decode operation: 8192.Use
Base58.Builder.setMaxDecodeLength(int)to raise (or effectively disable) the limit for trusted input.- Since:
- 1.23.0
- See Also:
-
DEFAULT_MAX_ENCODE_LENGTH
public static final int DEFAULT_MAX_ENCODE_LENGTHThe default maximum number of binary bytes accepted by a single encode operation: 8192.Use
Base58.Builder.setMaxEncodeLength(int)to raise (or effectively disable) the limit for trusted input.- Since:
- 1.23.0
- See Also:
-
ENCODE_TABLE
private static final byte[] ENCODE_TABLEBase58 alphabet: 123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz (excludes: 0, I, O, l). -
DECODE_TABLE
private static final byte[] DECODE_TABLEThis array is a lookup table that translates Unicode characters drawn from the "Base58 Alphabet" into their numeric equivalents (0-57). Characters that are not in the Base58 alphabet are marked with -1. -
maxDecodeLength
private final int maxDecodeLengthThe maximum number of encoded bytes accepted by a single decode operation. -
maxEncodeLength
private final int maxEncodeLengthThe maximum number of binary bytes accepted by a single encode operation.
-
-
Constructor Details
-
Base58
public Base58()Constructs a Base58 codec used for encoding and decoding. -
Base58
Constructs a Base58 codec used for encoding and decoding with custom configuration.- Parameters:
builder- The builder with custom configuration.
-
-
Method Details
-
builder
Creates a new Builder.To configure a new instance, use a
Base58.Builder. For example:Base58 base58 = Base58.builder() .setMaxEncodeLength(4096) .get()
- Returns:
- A new Builder.
-
calculateDecodeTable
private static byte[] calculateDecodeTable(byte[] encodeTable) Calculates a decode table for a given encode table.- Parameters:
encodeTable- that is used to determine decode lookup table.- Returns:
- A new decode table.
- Throws:
IllegalArgumentException- Thrown if the encode table does not contain exactly 58 unique entries.
-
toDecodeTable
private static byte[] toDecodeTable(byte[] encodeTable) Gets the decode table that matches the given encode table.- Parameters:
encodeTable- that is used to determine decode lookup table.- Returns:
- The matching decode table.
-
checkLength
-
code
private void code(byte[] array, int offset, int length, BaseNCodec.Context context, int maximum, String operation, BiConsumer<byte[], BaseNCodec.Context> consumer) -
convertFromBase58
Converts Base58 encoded data to binary.Uses 32-bit word arithmetic (
int[]withlongcarry) to convert the Base58 string to binary data, avoidingBigIntegerand its per-digit object allocation. Each Base58 digit is processed left-to-right using Horner's scheme:value = value * 58 + digit. AnwordsStartcursor tracks the leftmost word that contains data, so the inner loop only touches the active portion of the work buffer. The active range grows linearly with the number of digits, so total conversion work is quadratic in the input length.At each word position the carry satisfies
carry ≤ 57 + 58 × (2³²−1) < 2⁴⁰, which fits in a Javalong.Leading characters that match the first Base58 alphabet entry each represent a leading zero byte in the output.
- Parameters:
base58- The Base58 encoded data.context- The context for this decoding operation.- Throws:
IllegalArgumentException- Thrown if the Base58 data contains invalid characters or is longer than the configured maximum decode length.
-
convertToBase58
Converts accumulated binary data to Base58 encoding.Uses BigInteger arithmetic to convert the binary data to Base58. Leading zeros in the binary data are represented as the first character in the Base58 alphabet.
- Parameters:
accumulate- The binary data to encode.context- The context for this encoding operation.- Returns:
- The buffer containing the encoded data.
-
decode
Decodes the given Base58 encoded data.This implementation accumulates data internally. When length is less than 0 (EOF), the accumulated data is converted from Base58 to binary.
- Specified by:
decodein classBaseNCodec- Parameters:
array- The byte array containing Base58 encoded data.offset- The offset in the array to start from.length- The number of bytes to decode, or negative to signal EOF.context- The context for this decoding operation.- Throws:
IllegalArgumentException- Thrown when a problem is detected processing data.
-
encode
Encodes the given binary data as Base58.This implementation accumulates data internally. When length is less than 0 (EOF), the accumulated data is converted to Base58.
- Specified by:
encodein classBaseNCodec- Parameters:
array- The byte array containing binary data to encode.offset- The offset in the array to start from.length- The number of bytes to encode, or negative to signal EOF.context- The context for this encoding operation.
-
getEncodedLength
public long getEncodedLength(byte[] array) Gets the number of Base58 characters needed to encode the supplied array.The length depends on the input bytes, including leading zeros. This method observes the configured maximum encode length.
- Overrides:
getEncodedLengthin classBaseNCodec- Parameters:
array- The binary input to encode.- Returns:
- The number of Base58 characters that encoding the array produces.
- Throws:
IllegalArgumentException- Thrown if the input exceeds the configured maximum encode length.- Since:
- 1.23.0
-
getStringBuilder
Gets the Base58 string representation of the given binary data.Converts binary data to a BigInteger and divides by 58 repeatedly to get the Base58 digits. Handles leading zeros by counting them and appending the first character in the Base58 alphabet for each leading zero byte.
- Parameters:
accumulate- The binary data to convert.- Returns:
- A StringBuilder with the Base58 representation (not yet reversed).
-
isInAlphabet
protected boolean isInAlphabet(byte value) Tests whether theoctetis in the Base58 alphabet.- Specified by:
isInAlphabetin classBaseNCodec- Parameters:
value- The value to test.- Returns:
trueif the value is defined in the Base58 alphabetfalseotherwise.
-