Class BaseNCodec
- All Implemented Interfaces:
BinaryDecoder,BinaryEncoder,Decoder,Encoder
This class is thread-safe.
The default decoding policy is lenient. Strict decoding rejects trailing bits that cannot be produced by an encoding, including nonzero unused bits and impossible counts of final characters.
For Base32 and Base64, strict decoding additionally requires the exact canonical form produced by this instance's encoder. Re-encoding
successfully decoded input reproduces the input byte for byte. This includes the configured alphabet, padding, line length, and line separator, including
the final line separator when chunking is enabled. Whitespace and alphabet aliases are rejected unless the encoder produces them in that position.
Lenient decoding can map different encoded values to the same bytes. If an application uses encoded values as identifiers for blocklists, replay caches, or deduplication, validate canonical input before comparing those identifiers, or compare a consistently normalized representation throughout the application. Decoding alone does not authenticate input; signature verification must use the representation required by the signing protocol.
For example, select canonical Base32 decoding with:
Base32 base32 = Base32.builder().setDecodingPolicy(CodecPolicy.STRICT).get();
This instance requires the uppercase Base32 alphabet, padding for partial blocks, and no line separators. See Base64 for standard and URL-safe
Base64 examples.
Strict validation completes only at the end of the input. When decoding streams, consume the input stream to EOF or finish the output stream with
BaseNCodecOutputStream.eof() or BaseNCodecOutputStream.close(). A stream can emit decoded bytes before a later validation error.
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classBaseNCodec.AbstractBuilder<T,B extends BaseNCodec.AbstractBuilder<T, B>> BuildsBase64instances.(package private) static classHolds thread context so classes can be thread-safe. -
Field Summary
FieldsModifier and TypeFieldDescription(package private) static final byte[]Chunk separator per RFC 2045 section 2.1.private final intSize of chunk separator.(package private) final byte[]Decode table to use.protected static final CodecPolicyThe default decoding policy.private final CodecPolicyDecoding policy, including canonical validation for Base32 and Base64.private static final intprivate static final intDefines the default buffer size - currently 8192 - must be large enough for at least one encoded block+separator(package private) static final byte[]The empty byte array.private final intNumber of bytes in each full block of encoded data, for example 3 for Base64 and 8 for Base32(package private) final byte[]Encode table.(package private) static final intEnd-of-file marker.protected final intChunk size for encoding and strict decoding.protected static final intMask used to extract 8 bits, used in decoding bytesprivate static final intThe maximum size buffer to allocate.static final intMIME chunk size per RFC 2045 section 6.8.protected final bytePad byte.protected final byteDeprecated.protected static final byteByte used to pad output.static final intPEM chunk size per RFC 1421 section 4.3.2.4.private final intNumber of bytes in each full block of unencoded data, for example 4 for Base64 and 5 for Base32 -
Constructor Summary
ConstructorsModifierConstructorDescriptionprotectedBaseNCodec(int unencodedBlockSize, int encodedBlockSize, int lineLength, int chunkSeparatorLength) Deprecated.protectedBaseNCodec(int unencodedBlockSize, int encodedBlockSize, int lineLength, int chunkSeparatorLength, byte pad) Deprecated.protectedBaseNCodec(int unencodedBlockSize, int encodedBlockSize, int lineLength, int chunkSeparatorLength, byte pad, CodecPolicy decodingPolicy) Deprecated.protectedBaseNCodec(BaseNCodec.AbstractBuilder<?, ?> builder) Constructs a new instance for a subclass. -
Method Summary
Modifier and TypeMethodDescription(package private) intavailable(BaseNCodec.Context context) Returns the amount of buffered data available for reading.(package private) static voidcode(boolean doEncode, BaseNCodec baseNCodec, byte[] buf, int offset, int len, BaseNCodec.Context context) protected booleancontainsAlphabetOrPad(byte[] arrayOctet) Tests a given byte array to see if it contains any characters within the alphabet or PAD.private static intcreatePositiveCapacity(int minCapacity) Create a positive capacity at least as large the minimum required capacity.byte[]decode(byte[] array) Decodes a byte[] containing characters in the Base-N alphabet.(package private) abstract voiddecode(byte[] array, int offset, int length, BaseNCodec.Context context) Decodes a byte[] containing characters in the Base-N alphabet into a temporary context buffer.Decodes an Object using the Base-N algorithm.byte[]Decodes a String containing characters in the Base-N alphabet.byte[]encode(byte[] array) Encodes a byte[] containing binary data, into a byte[] containing characters in the alphabet.byte[]encode(byte[] array, int offset, int length) Encodes a byte[] containing binary data, into a byte[] containing characters in the alphabet.(package private) abstract voidencode(byte[] array, int offset, int length, BaseNCodec.Context context) Encodes a byte[] containing characters in the Base-N alphabet into a temporary context buffer.Encodes an Object using the Base-N algorithm.encodeAsString(byte[] array) Encodes a byte[] containing binary data, into a String containing characters in the appropriate alphabet.encodeToString(byte[] array) Encodes a byte[] containing binary data, into a String containing characters in the Base-N alphabet.protected byte[]ensureBufferSize(int size, BaseNCodec.Context context) Ensures that the buffer has room forsizebytesstatic byte[]Gets a copy of the chunk separator per RFC 2045 section 2.1.Gets the decoding behavior policy.protected intGets the default buffer size.longgetEncodedLength(byte[] array) Gets the amount of space needed to encode the supplied array.private static intgte0(int value) (package private) booleanhasData(BaseNCodec.Context context) Tests whether this object has buffered data for reading.protected abstract booleanisInAlphabet(byte value) Tests whether or not theoctetis in the current alphabet.booleanisInAlphabet(byte[] arrayOctet, boolean allowWhitespacePad) Tests a given byte array to see if it contains only valid characters within the alphabet.booleanisInAlphabet(String basen) Tests a given String to see if it contains only valid characters within the alphabet.booleanTests whether decoding behavior is strict.protected static booleanisWhiteSpace(byte byteToCheck) Deprecated.(package private) intreadResults(byte[] b, int position, int available, BaseNCodec.Context context) Reads buffered data into the provided byte[] array, starting at position bPos, up to a maximum of bAvail bytes.private static byte[]resizeBuffer(BaseNCodec.Context context, int minCapacity) Increases our buffer by theDEFAULT_BUFFER_RESIZE_FACTOR.(package private) static byte[]toUnsignedBytes(BigInteger value) Returns a byte-array representation of aBigIntegerwithout sign bit.(package private) booleanvalidateCanonicalByte(int value, byte[] lineSeparator, boolean padded, BaseNCodec.Context context) Validates a byte against the canonical Base32 or Base64 encoding, consuming padding and line separators.(package private) voidvalidateCanonicalEnd(boolean padded, BaseNCodec.Context context) Validates the end of a canonical Base32 or Base64 encoding.private voidvalidateCanonicalPadding(boolean padded, BaseNCodec.Context context) Validates the number of padding bytes at the end of a line or input.
-
Field Details
-
EOF
static final int EOFEnd-of-file marker.- Since:
- 1.7
- See Also:
-
MIME_CHUNK_SIZE
public static final int MIME_CHUNK_SIZEMIME chunk size per RFC 2045 section 6.8.The 76 character limit does not count the trailing CRLF, but counts all other characters, including any equal signs.
- See Also:
-
PEM_CHUNK_SIZE
public static final int PEM_CHUNK_SIZEPEM chunk size per RFC 1421 section 4.3.2.4.The 64 character limit does not count the trailing CRLF, but counts all other characters, including any equal signs.
-
DEFAULT_BUFFER_RESIZE_FACTOR
private static final int DEFAULT_BUFFER_RESIZE_FACTOR- See Also:
-
DEFAULT_BUFFER_SIZE
private static final int DEFAULT_BUFFER_SIZEDefines the default buffer size - currently 8192 - must be large enough for at least one encoded block+separator- See Also:
-
MAX_BUFFER_SIZE
private static final int MAX_BUFFER_SIZEThe maximum size buffer to allocate.This is set to the same size used in the JDK
ArrayList:Some VMs reserve some header words in an array. Attempts to allocate larger arrays may result in OutOfMemoryError: Requested array size exceeds VM limit.
- See Also:
-
MASK_8BITS
protected static final int MASK_8BITSMask used to extract 8 bits, used in decoding bytes- See Also:
-
PAD_DEFAULT
protected static final byte PAD_DEFAULTByte used to pad output.- See Also:
-
DECODING_POLICY_DEFAULT
The default decoding policy.- Since:
- 1.15
-
CHUNK_SEPARATOR
static final byte[] CHUNK_SEPARATORChunk separator per RFC 2045 section 2.1.- See Also:
-
EMPTY_BYTE_ARRAY
static final byte[] EMPTY_BYTE_ARRAYThe empty byte array. -
PAD
Deprecated.Usepad. Will be removed in 2.0.Deprecated: Will be removed in 2.0.Instance variable just in case it needs to vary later
- See Also:
-
pad
protected final byte padPad byte. Instance variable just in case it needs to vary later. -
unencodedBlockSize
private final int unencodedBlockSizeNumber of bytes in each full block of unencoded data, for example 4 for Base64 and 5 for Base32 -
encodedBlockSize
private final int encodedBlockSizeNumber of bytes in each full block of encoded data, for example 3 for Base64 and 8 for Base32 -
lineLength
protected final int lineLengthChunk size for encoding and strict decoding. A value of zero or less implies no chunking of the encoded data. Rounded down to the nearest multiple of encodedBlockSize. -
chunkSeparatorLength
private final int chunkSeparatorLengthSize of chunk separator. Not used unlesslineLength> 0. -
decodingPolicy
Decoding policy, including canonical validation for Base32 and Base64. -
decodeTable
final byte[] decodeTableDecode table to use. -
encodeTable
final byte[] encodeTableEncode table.
-
-
Constructor Details
-
BaseNCodec
Constructs a new instance for a subclass.- Parameters:
builder- How to build this portion of the instance.- Since:
- 1.20.0
-
BaseNCodec
@Deprecated protected BaseNCodec(int unencodedBlockSize, int encodedBlockSize, int lineLength, int chunkSeparatorLength) Deprecated.Constructs a new instance.Note
lineLengthis rounded down to the nearest multiple of the encoded block size. IfchunkSeparatorLengthis zero, then chunking is disabled.- Parameters:
unencodedBlockSize- The size of an unencoded block (for example Base64 = 3).encodedBlockSize- The size of an encoded block (for example Base64 = 4).lineLength- if > 0, use chunking with a lengthlineLength.chunkSeparatorLength- The chunk separator length, if relevant.
-
BaseNCodec
@Deprecated protected BaseNCodec(int unencodedBlockSize, int encodedBlockSize, int lineLength, int chunkSeparatorLength, byte pad) Deprecated.Constructs a new instance.Note
lineLengthis rounded down to the nearest multiple of the encoded block size. IfchunkSeparatorLengthis zero, then chunking is disabled.- Parameters:
unencodedBlockSize- The size of an unencoded block (for example Base64 = 3).encodedBlockSize- The size of an encoded block (for example Base64 = 4).lineLength- if > 0, use chunking with a lengthlineLength.chunkSeparatorLength- The chunk separator length, if relevant.pad- byte used as padding byte.
-
BaseNCodec
@Deprecated protected BaseNCodec(int unencodedBlockSize, int encodedBlockSize, int lineLength, int chunkSeparatorLength, byte pad, CodecPolicy decodingPolicy) Deprecated.Constructs a new instance.Note
lineLengthis rounded down to the nearest multiple of the encoded block size. IfchunkSeparatorLengthis zero, then chunking is disabled.- Parameters:
unencodedBlockSize- The size of an unencoded block (for example Base64 = 3).encodedBlockSize- The size of an encoded block (for example Base64 = 4).lineLength- if > 0, use chunking with a lengthlineLength.chunkSeparatorLength- The chunk separator length, if relevant.pad- byte used as padding byte.decodingPolicy- Decoding policy.- Since:
- 1.15
-
-
Method Details
-
code
static void code(boolean doEncode, BaseNCodec baseNCodec, byte[] buf, int offset, int len, BaseNCodec.Context context) throws IOException - Throws:
IOException
-
createPositiveCapacity
private static int createPositiveCapacity(int minCapacity) Create a positive capacity at least as large the minimum required capacity. If the minimum capacity is negative then this throws an OutOfMemoryError as no array can be allocated.- Parameters:
minCapacity- The minimum capacity.- Returns:
- The capacity.
- Throws:
OutOfMemoryError- Thrown if theminCapacityis negative.
-
getChunkSeparator
public static byte[] getChunkSeparator()Gets a copy of the chunk separator per RFC 2045 section 2.1.- Returns:
- The chunk separator.
- Since:
- 1.15
- See Also:
-
gte0
private static int gte0(int value) -
isWhiteSpace
Deprecated.Tests if a byte value is whitespace or not.- Parameters:
byteToCheck- The byte to check.- Returns:
- true if byte is whitespace, false otherwise.
- See Also:
-
resizeBuffer
Increases our buffer by theDEFAULT_BUFFER_RESIZE_FACTOR.- Parameters:
context- The context to be used.minCapacity- The minimum required capacity.- Returns:
- The resized byte[] buffer.
- Throws:
OutOfMemoryError- Thrown if theminCapacityis negative.
-
toUnsignedBytes
Returns a byte-array representation of aBigIntegerwithout sign bit.The value
BigInteger.ZEROmaps to an empty array.- Parameters:
value-BigIntegerto be converted.- Returns:
- A byte array representation of the BigInteger parameter.
-
available
Returns the amount of buffered data available for reading.- Parameters:
context- The context to be used.- Returns:
- The amount of buffered data available for reading.
-
containsAlphabetOrPad
protected boolean containsAlphabetOrPad(byte[] arrayOctet) Tests a given byte array to see if it contains any characters within the alphabet or PAD. Intended for use in checking line-ending arrays.- Parameters:
arrayOctet- byte array to test.- Returns:
trueif any byte is a valid character in the alphabet or PAD;falseotherwise.
-
decode
public byte[] decode(byte[] array) Decodes a byte[] containing characters in the Base-N alphabet.Uses this instance's decoding policy. Lenient decoding can accept multiple representations of the same bytes. For canonical Base32 or Base64 input, configure
CodecPolicy.STRICT; see the class documentation for examples and guidance on comparing encoded values.- Specified by:
decodein interfaceBinaryDecoder- Parameters:
array- A byte array containing Base-N character data.- Returns:
- A byte array containing binary data.
- Throws:
IllegalArgumentException- Thrown when a problem is detected processing data.
-
decode
Decodes a byte[] containing characters in the Base-N alphabet into a temporary context buffer.This method is package protected for access from I/O streams.
- Parameters:
array- A byte array containing Base-N character data.offset- initial offset of the subarray.length- length of the subarray.- Throws:
IllegalArgumentException- Thrown when a problem is detected processing data.
-
decode
Decodes an Object using the Base-N algorithm. This method is provided in order to satisfy the requirements of the Decoder interface, and will throw a DecoderException if the supplied object is not of type byte[] or String.Uses this instance's decoding policy. Lenient decoding can accept multiple representations of the same bytes. For canonical Base32 or Base64 input, configure
CodecPolicy.STRICT; see the class documentation for examples and guidance on comparing encoded values.- Specified by:
decodein interfaceDecoder- Parameters:
obj- Object to decode.- Returns:
- An object (of type byte[]) containing the binary data which corresponds to the byte[] or String supplied.
- Throws:
DecoderException- Thrown if the parameter supplied is not of type byte[].IllegalArgumentException- Thrown when a problem is detected processing data.
-
decode
Decodes a String containing characters in the Base-N alphabet.Uses this instance's decoding policy. Lenient decoding can accept multiple representations of the same bytes. For canonical Base32 or Base64 input, configure
CodecPolicy.STRICT; see the class documentation for examples and guidance on comparing encoded values.- Parameters:
array- A String containing Base-N character data.- Returns:
- A byte array containing binary data.
- Throws:
IllegalArgumentException- Thrown when a problem is detected processing data.
-
encode
public byte[] encode(byte[] array) Encodes a byte[] containing binary data, into a byte[] containing characters in the alphabet.- Specified by:
encodein interfaceBinaryEncoder- Parameters:
array- A byte array containing binary data.- Returns:
- A byte array containing only the base N alphabetic character data.
- Throws:
IllegalArgumentException- Thrown when a problem is detected processing data.
-
encode
public byte[] encode(byte[] array, int offset, int length) Encodes a byte[] containing binary data, into a byte[] containing characters in the alphabet.- Parameters:
array- A byte array containing binary data.offset- initial offset of the subarray.length- length of the subarray.- Returns:
- A byte array containing only the base N alphabetic character data.
- Throws:
IllegalArgumentException- Thrown when a problem is detected processing data.- Since:
- 1.11
-
encode
Encodes a byte[] containing characters in the Base-N alphabet into a temporary context buffer.This method is package protected for access from I/O streams.
- Parameters:
array- A byte array containing Base-N character data.offset- initial offset of the subarray.length- length of the subarray.- Throws:
IllegalArgumentException- Thrown when a problem is detected processing data.
-
encode
Encodes an Object using the Base-N algorithm. This method is provided in order to satisfy the requirements of the Encoder interface, and will throw an EncoderException if the supplied object is not of type byte[].- Specified by:
encodein interfaceEncoder- Parameters:
obj- Object to encode.- Returns:
- An object (of type byte[]) containing the Base-N encoded data which corresponds to the byte[] supplied.
- Throws:
EncoderException- Thrown if the parameter supplied is not of type byte[].
-
encodeAsString
Encodes a byte[] containing binary data, into a String containing characters in the appropriate alphabet. Uses UTF8 encoding.This is a duplicate of
encodeToString(byte[]); it was merged during refactoring.- Parameters:
array- A byte array containing binary data.- Returns:
- String containing only character data in the appropriate alphabet.
- Since:
- 1.5
-
encodeToString
Encodes a byte[] containing binary data, into a String containing characters in the Base-N alphabet. Uses UTF8 encoding.- Parameters:
array- A byte array containing binary data.- Returns:
- A String containing only Base-N character data.
-
ensureBufferSize
Ensures that the buffer has room forsizebytes- Parameters:
size- minimum spare space required.context- The context to be used.- Returns:
- The buffer.
-
getCodecPolicy
Gets the decoding behavior policy.The default is lenient. Strict decoding rejects invalid trailing bits and, for Base32 and Base64, noncanonical input as described in this class.
- Returns:
- The decoding policy.
- Since:
- 1.15
-
getDefaultBufferSize
protected int getDefaultBufferSize()Gets the default buffer size. Can be overridden.- Returns:
- The default buffer size.
-
getEncodedLength
public long getEncodedLength(byte[] array) Gets the amount of space needed to encode the supplied array.- Parameters:
array- byte[] array which will later be encoded.- Returns:
- amount of space needed to encode the supplied array. Returns a long since a max-len array will require > Integer.MAX_VALUE.
-
hasData
Tests whether this object has buffered data for reading.- Parameters:
context- The context to be used.- Returns:
- true if there is data still available for reading.
-
isInAlphabet
protected abstract boolean isInAlphabet(byte value) Tests whether or not theoctetis in the current alphabet. Does not allow whitespace or pad.- Parameters:
value- The value to test.- Returns:
trueif the value is defined in the current alphabet,falseotherwise.
-
isInAlphabet
public boolean isInAlphabet(byte[] arrayOctet, boolean allowWhitespacePad) Tests a given byte array to see if it contains only valid characters within the alphabet. The method optionally treats whitespace and pad as valid.- Parameters:
arrayOctet- byte array to test.allowWhitespacePad- iftrue, then whitespace and PAD are also allowed.- Returns:
trueif all bytes are valid characters in the alphabet or if the byte array is empty;false, otherwise.
-
isInAlphabet
Tests a given String to see if it contains only valid characters within the alphabet. The method treats whitespace and PAD as valid.- Parameters:
basen- String to test.- Returns:
trueif all characters in the String are valid characters in the alphabet or if the String is empty;false, otherwise.- See Also:
-
isStrictDecoding
public boolean isStrictDecoding()Tests whether decoding behavior is strict.Strict decoding rejects invalid trailing bits and, for Base32 and Base64, noncanonical input as described in this class.
- Returns:
- true if using strict decoding.
- Since:
- 1.15
-
readResults
Reads buffered data into the provided byte[] array, starting at position bPos, up to a maximum of bAvail bytes. Returns how many bytes were actually extracted.Package private for access from I/O streams.
- Parameters:
b- byte[] array to extract the buffered data into.position- position in byte[] array to start extraction at.available- amount of bytes we're allowed to extract. We may extract fewer (if fewer are available).context- The context to be used.- Returns:
- The number of bytes successfully extracted into the provided byte[] array.
-
validateCanonicalByte
boolean validateCanonicalByte(int value, byte[] lineSeparator, boolean padded, BaseNCodec.Context context) Validates a byte against the canonical Base32 or Base64 encoding, consuming padding and line separators.- Parameters:
value- The unsigned input byte.lineSeparator- The configured line separator.padded- Whether the encoder pads partial blocks.context- The decoding context, whose modulus counts alphabet characters only.- Returns:
- Whether the byte is an alphabet character to decode.
- Throws:
IllegalArgumentException- Thrown if the byte cannot occur in a canonical encoding.
-
validateCanonicalEnd
Validates the end of a canonical Base32 or Base64 encoding.- Parameters:
padded- Whether the encoder pads partial blocks.context- The decoding context.- Throws:
IllegalArgumentException- Thrown if padding or the final line separator is incomplete.
-
validateCanonicalPadding
Validates the number of padding bytes at the end of a line or input.- Parameters:
padded- Whether the encoder pads partial blocks.context- The decoding context.- Throws:
IllegalArgumentException- Thrown if required padding is missing.
-
pad.