Class Base64
- All Implemented Interfaces:
BinaryDecoder,BinaryEncoder,Decoder,Encoder
This class implements RFC 2045 6.8. Base64 Content-Transfer-Encoding.
The class can be parameterized in the following manner with its Base64.Builder:
- URL-safe mode: Default off.
- Line length: Default 76. Line length that aren't multiples of 4 will still essentially end up being multiples of 4 in the encoded data.
- Line separator: Default is CRLF (
"\r\n") - Strict or lenient decoding policy; default is
CodecPolicy.LENIENT. - Custom decoding table.
- Custom encoding table.
- Padding; defaults is
'='.
The URL-safe parameter selects the encoding alphabet. Lenient decoding seamlessly handles both modes; strict decoding requires the encoding alphabet. See also
Builder#setDecodeTableFormat(DecodeTableFormat).
Since this class operates directly on byte streams, and not character streams, it is hard-coded to only encode/decode character encodings which are compatible with the lower 127 ASCII chart (ISO-8859-1, Windows-1252, UTF-8, etc).
This class is thread-safe.
To configure a new instance, use a Base64.Builder. For example:
Base64 base64 = Base64.builder()
.setDecodingPolicy(CodecPolicy.LENIENT) // default is lenient, null resets to default
.setEncodeTable(customEncodeTable) // default is built in, null resets to default
.setLineLength(0) // default is none
.setLineSeparator('\r', '\n') // default is CR LF, null resets to default
.setPadding('=') // default is '='
.setUrlSafe(false) // default is false
.get()
The static decoding convenience methods use CodecPolicy.LENIENT. They accept noncanonical input, so different encoded strings can decode to the
same bytes. Selecting a standard or URL-safe decode table does not enable strict validation. To require canonical input, configure a strict instance:
Base64 standard = Base64.builder().setDecodingPolicy(CodecPolicy.STRICT).get(); Base64 urlSafe = Base64.builder().setUrlSafe(true).setDecodingPolicy(CodecPolicy.STRICT).get();
These instances accept unchunked input using their respective encoding alphabets. The standard instance requires padding for partial blocks; the URL-safe
instance requires unpadded input. See BaseNCodec for the full canonical decoding contract and guidance on comparing encoded values.
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classBuildsBase64instances.static enumEnumerates the Base64 table format to be used on decoding.Nested 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 intBASE64 characters are 6 bits in length.private static final intprivate static final intprivate static final byte[]This array is a lookup table that translates Unicode characters drawn from the "Base64 Alphabet" (as specified in RFC 2045 Table 1: The Base64 Alphabet) into their 6-bit positive integer equivalents.private static final intprivate final intConvenience variable to help us determine when our buffer is going to run out of room and needs resizing.private final booleanprivate final booleanprivate final byte[]Line separator for encoding and strict decoding.private static final intMask used to extract 2 bits, used when decoding final trailing character.private static final intMask used to extract 4 bits, used when decoding final trailing character.private static final intMask used to extract 6 bits, used when encodingprivate static final byte[]This array is a lookup table that translates Unicode characters drawn from the "Base64 Alphabet" (as specified in RFC 2045 Table 1: The Base64 Alphabet) into their 6-bit positive integer equivalents.private static final byte[]This array is a lookup table that translates 6-bit positive integer index values into their "Base64 Alphabet" equivalents as specified in RFC 2045 Table 1: The Base64 Alphabet.private static final byte[]This array is a lookup table that translates Unicode characters drawn from the "Base64 URL-safe Alphabet" (as specified in RFC 4648 Table 2: The "URL and Filename safe" Base 64 Alphabet) into their 6-bit positive integer equivalents.private static final byte[]This is a copy of the STANDARD_ENCODE_TABLE above, but with + and / changed to - and _ to make the encoded Base64 results more URL-SAFE.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
ConstructorsModifierConstructorDescriptionBase64()Constructs a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.Base64(boolean urlSafe) Deprecated.Base64(int lineLength) Deprecated.Usebuilder()andBase64.Builder.Base64(int lineLength, byte[] lineSeparator) Deprecated.Usebuilder()andBase64.Builder.Base64(int lineLength, byte[] lineSeparator, boolean urlSafe) Deprecated.Usebuilder()andBase64.Builder.Base64(int lineLength, byte[] lineSeparator, boolean urlSafe, CodecPolicy decodingPolicy) Deprecated.Usebuilder()andBase64.Builder.privateBase64(Base64.Builder builder) -
Method Summary
Modifier and TypeMethodDescriptionstatic Base64.Builderbuilder()Creates a new Builder.private static byte[]calculateDecodeTable(byte[] encodeTable) Calculates a decode table for a given encode table.private static booleancontains(byte[] bytes, byte value) (package private) voiddecode(byte[] input, int inPos, int inAvail, BaseNCodec.Context context) Decodes all of the provided data, starting at inPos, for inAvail bytes.static byte[]decodeBase64(byte[] base64Data) Decodes Base64 data into octets using lenient decoding.static byte[]decodeBase64(String base64String) Decodes a Base64 string into octets using lenient decoding.static byte[]decodeBase64Standard(byte[] base64Data) Decodes standard Base64 data into octets using lenient decoding.static byte[]decodeBase64Standard(String base64String) Decodes a standard Base64 string into octets using lenient decoding.static byte[]decodeBase64UrlSafe(byte[] base64Data) Decodes URL-safe Base64 data into octets using lenient decoding.static byte[]decodeBase64UrlSafe(String base64String) Decodes a URL-safe Base64 string into octets using lenient decoding.static BigIntegerdecodeInteger(byte[] array) Decodes a byte64-encoded integer according to crypto standards such as W3C's XML-Signature.(package private) voidencode(byte[] in, int inPos, int inAvail, BaseNCodec.Context context) Encodes all of the provided data, starting at inPos, for inAvail bytes.static byte[]encodeBase64(byte[] binaryData) Encodes binary data using the base64 algorithm but does not chunk the output.static byte[]encodeBase64(byte[] binaryData, boolean isChunked) Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks.static byte[]encodeBase64(byte[] binaryData, boolean isChunked, boolean urlSafe) Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks.static byte[]encodeBase64(byte[] binaryData, boolean isChunked, boolean urlSafe, int maxResultSize) Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks.static byte[]encodeBase64Chunked(byte[] binaryData) Encodes binary data using the base64 algorithm and chunks the encoded output into 76 character blocksstatic StringencodeBase64String(byte[] binaryData) Encodes binary data using the base64 algorithm but does not chunk the output.static byte[]encodeBase64URLSafe(byte[] binaryData) Encodes binary data using a URL-safe variation of the base64 algorithm but does not chunk the output.static StringencodeBase64URLSafeString(byte[] binaryData) Encodes binary data using a URL-safe variation of the base64 algorithm but does not chunk the output.static byte[]encodeInteger(BigInteger bigInteger) Encodes to a byte64-encoded integer according to crypto standards such as W3C's XML-Signature.(package private) byte[]Gets the line separator (for testing only).static booleanisArrayByteBase64(byte[] arrayOctet) Deprecated.1.5 UseisBase64(byte[]), will be removed in 2.0.static booleanisBase64(byte octet) Tests whether or not theoctetis in the Base64 alphabet.static booleanisBase64(byte[] arrayOctet) Tests a given byte array to see if it contains only valid characters within the Base64 alphabet.static booleanTests a given String to see if it contains only valid characters within the Base64 alphabet.static booleanisBase64Standard(byte octet) Tests whether or not theoctetis in the standard Base64 alphabet.static booleanisBase64Standard(byte[] arrayOctet) Tests a given byte array to see if it contains only valid characters within the standard Base64 alphabet.static booleanisBase64Standard(String base64) Tests a given String to see if it contains only valid characters within the standard Base64 alphabet.static booleanisBase64Url(byte octet) Tests whether or not theoctetis in the URL-safe Base64 alphabet.static booleanisBase64Url(byte[] arrayOctet) Tests a given byte array to see if it contains only valid characters within the URL-safe Base64 alphabet.static booleanisBase64Url(String base64) Tests a given String to see if it contains only valid characters within the URL-safe Base64 alphabet.protected booleanisInAlphabet(byte octet) Tests whether theoctetis in the Base64 alphabet.booleanTests whether the current encoding mode is URL-safe.private static byte[]toDecodeTable(byte[] encodeTable) (package private) static byte[]toUrlSafeEncodeTable(boolean urlSafe) private voidvalidateCharacter(int emptyBitsMask, BaseNCodec.Context context) Validates whether decoding the final trailing character is possible in the context of the set of possible Base64 values.private voidValidates whether decoding allows an entire final trailing character that cannot be used for a complete byte.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, getEncodedLength, hasData, isInAlphabet, isInAlphabet, isStrictDecoding, isWhiteSpace, readResults, toUnsignedBytes, validateCanonicalByte, validateCanonicalEnd
-
Field Details
-
BITS_PER_ENCODED_BYTE
private static final int BITS_PER_ENCODED_BYTEBASE64 characters are 6 bits in length. They are formed by taking a block of 3 octets to form a 24-bit string, which is converted into 4 BASE64 characters.- See Also:
-
BYTES_PER_UNENCODED_BLOCK
private static final int BYTES_PER_UNENCODED_BLOCK- See Also:
-
BYTES_PER_ENCODED_BLOCK
private static final int BYTES_PER_ENCODED_BLOCK- See Also:
-
DECODING_TABLE_LENGTH
private static final int DECODING_TABLE_LENGTH- See Also:
-
STANDARD_ENCODE_TABLE
private static final byte[] STANDARD_ENCODE_TABLEThis array is a lookup table that translates 6-bit positive integer index values into their "Base64 Alphabet" equivalents as specified in RFC 2045 Table 1: The Base64 Alphabet.Thanks to "commons" project in ws.apache.org for this code. https://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/
-
URL_SAFE_ENCODE_TABLE
private static final byte[] URL_SAFE_ENCODE_TABLEThis is a copy of the STANDARD_ENCODE_TABLE above, but with + and / changed to - and _ to make the encoded Base64 results more URL-SAFE. This table is only used when the Base64's mode is set to URL-SAFE. -
DECODE_TABLE
private static final byte[] DECODE_TABLEThis array is a lookup table that translates Unicode characters drawn from the "Base64 Alphabet" (as specified in RFC 2045 Table 1: The Base64 Alphabet) into their 6-bit positive integer equivalents. Characters that are not in the Base64 or Base64 URL-safe alphabets but fall within the bounds of the array are translated to -1.The characters '+' and '-' both decode to 62. '/' and '_' both decode to 63. This means decoder seamlessly handles both URL_SAFE and STANDARD base64. (The encoder, on the other hand, needs to know ahead of time what to emit).
Thanks to "commons" project in ws.apache.org for this code. https://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/
-
STANDARD_DECODE_TABLE
private static final byte[] STANDARD_DECODE_TABLEThis array is a lookup table that translates Unicode characters drawn from the "Base64 Alphabet" (as specified in RFC 2045 Table 1: The Base64 Alphabet) into their 6-bit positive integer equivalents. Characters that are not in the Base64 alphabet but fall within the bounds of the array are translated to -1. This decoding table handles only the standard base64 characters, such as '+' and '/'. The "url-safe" characters such as '-' and '_' are not supported by the table. -
URL_SAFE_DECODE_TABLE
private static final byte[] URL_SAFE_DECODE_TABLEThis array is a lookup table that translates Unicode characters drawn from the "Base64 URL-safe Alphabet" (as specified in RFC 4648 Table 2: The "URL and Filename safe" Base 64 Alphabet) into their 6-bit positive integer equivalents. Characters that are not in the Base64 URL-safe alphabet but fall within the bounds of the array are translated to -1. This decoding table handles only the URL-safe base64 characters, such as '-' and '_'. The standard characters such as '+' and '/' are not supported by the table. -
MASK_6_BITS
private static final int MASK_6_BITSMask used to extract 6 bits, used when encoding- See Also:
-
MASK_4_BITS
private static final int MASK_4_BITSMask used to extract 4 bits, used when decoding final trailing character.- See Also:
-
MASK_2_BITS
private static final int MASK_2_BITSMask used to extract 2 bits, used when decoding final trailing character.- See Also:
-
lineSeparator
private final byte[] lineSeparatorLine separator for encoding and strict decoding. Only used if lineLength > 0. -
encodeSize
private final int encodeSizeConvenience variable to help us determine when our buffer is going to run out of room and needs resizing.encodeSize = 4 + lineSeparator.length; -
isUrlSafe
private final boolean isUrlSafe -
isStandardEncodeTable
private final boolean isStandardEncodeTable
-
-
Constructor Details
-
Base64
public Base64()Constructs a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.When encoding the line length is 0 (no chunking), and the encoding table is STANDARD_ENCODE_TABLE.
When decoding leniently all variants are supported. Strict decoding requires the configured encoding alphabet and layout.
-
Base64
Deprecated.Usebuilder()andBase64.Builder.Constructs a Base64 codec used for decoding (all modes) and encoding in the given URL-safe mode.When encoding the line length is 76, the line separator is CRLF, and the encoding table is STANDARD_ENCODE_TABLE.
When decoding leniently all variants are supported. Strict decoding requires the configured encoding alphabet and layout.
- Parameters:
urlSafe- iftrue, URL-safe encoding is used. In most cases this should be set tofalse.- Since:
- 1.4
-
Base64
-
Base64
Deprecated.Usebuilder()andBase64.Builder.Constructs a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.When encoding the line length is given in the constructor, the line separator is CRLF, and the encoding table is STANDARD_ENCODE_TABLE.
Line lengths that aren't multiples of 4 will still essentially end up being multiples of 4 in the encoded data.
When decoding leniently all variants are supported. Strict decoding requires the configured encoding alphabet and layout.
- Parameters:
lineLength- Each line of encoded data will be at most of the given length (rounded down to the nearest multiple of 4). If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when decoding leniently.- Since:
- 1.4
-
Base64
Deprecated.Usebuilder()andBase64.Builder.Constructs a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.When encoding the line length and line separator are given in the constructor, and the encoding table is STANDARD_ENCODE_TABLE.
Line lengths that aren't multiples of 4 will still essentially end up being multiples of 4 in the encoded data.
When decoding leniently all variants are supported. Strict decoding requires the configured encoding alphabet and layout.
- Parameters:
lineLength- Each line of encoded data will be at most of the given length (rounded down to the nearest multiple of 4). If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when decoding leniently.lineSeparator- Each line of encoded data will end with this sequence of bytes.- Throws:
IllegalArgumentException- Thrown when the provided lineSeparator included some base64 characters.- Since:
- 1.4
-
Base64
Deprecated.Usebuilder()andBase64.Builder.Constructs a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.When encoding the line length and line separator are given in the constructor, and the encoding table is STANDARD_ENCODE_TABLE.
Line lengths that aren't multiples of 4 will still essentially end up being multiples of 4 in the encoded data.
When decoding leniently all variants are supported. Strict decoding requires the configured encoding alphabet and layout.
- Parameters:
lineLength- Each line of encoded data will be at most of the given length (rounded down to the nearest multiple of 4). If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when decoding leniently.lineSeparator- Each line of encoded data will end with this sequence of bytes.urlSafe- Instead of emitting '+' and '/' we emit '-' and '_' respectively. urlSafe is only applied to encode operations. Decoding seamlessly handles both modes. No padding is added when using the URL-safe alphabet.- Throws:
IllegalArgumentException- Thrown when thelineSeparatorcontains Base64 characters.- Since:
- 1.4
-
Base64
@Deprecated public Base64(int lineLength, byte[] lineSeparator, boolean urlSafe, CodecPolicy decodingPolicy) Deprecated.Usebuilder()andBase64.Builder.Constructs a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.When encoding the line length and line separator are given in the constructor, and the encoding table is STANDARD_ENCODE_TABLE.
Line lengths that aren't multiples of 4 will still essentially end up being multiples of 4 in the encoded data.
When decoding leniently all variants are supported. Strict decoding requires the configured encoding alphabet and layout.
- Parameters:
lineLength- Each line of encoded data will be at most of the given length (rounded down to the nearest multiple of 4). If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when decoding leniently.lineSeparator- Each line of encoded data will end with this sequence of bytes.urlSafe- Instead of emitting '+' and '/' we emit '-' and '_' respectively. Strict decoding requires this alphabet. Lenient decoding handles both modes. No padding is added when using the URL-safe alphabet.decodingPolicy- The decoding policy.- Throws:
IllegalArgumentException- Thrown when thelineSeparatorcontains Base64 characters.- Since:
- 1.15
-
-
Method Details
-
builder
Creates a new Builder.To configure a new instance, use a
Base64.Builder. For example:Base64 base64 = Base64.builder() .setDecodingPolicy(CodecPolicy.LENIENT) // default is lenient, null resets to default .setEncodeTable(customEncodeTable) // default is built in, null resets to default .setLineLength(0) // default is none .setLineSeparator('\r', '\n') // default is CR LF, null resets to default .setPadding('=') // default is '=' .setUrlSafe(false) // default is false .get()- Returns:
- A new Builder.
- Since:
- 1.17.0
-
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.
-
contains
private static boolean contains(byte[] bytes, byte value) -
decodeBase64
public static byte[] decodeBase64(byte[] base64Data) Decodes Base64 data into octets using lenient decoding.This method uses the standard and URL-safe alphabets. It skips unsupported input, discards data after the first padding character, and accepts noncanonical padding and trailing bits. Different encoded inputs can therefore produce the same decoded bytes. This method does not validate canonical input.
For canonical decoding, use
Base64.builder().setDecodingPolicy(CodecPolicy.STRICT).get().decode(base64Data). SeeBaseNCodecfor guidance on comparing encoded values.- Parameters:
base64Data- Byte array containing Base64 data.- Returns:
- New array containing decoded data.
- Throws:
IllegalArgumentException- Thrown when a problem is detected processing data.
-
decodeBase64
Decodes a Base64 string into octets using lenient decoding.This method uses the standard and URL-safe alphabets. It skips unsupported input, discards data after the first padding character, and accepts noncanonical padding and trailing bits. Different encoded inputs can therefore produce the same decoded bytes. This method does not validate canonical input.
For canonical decoding, use
Base64.builder().setDecodingPolicy(CodecPolicy.STRICT).get().decode(base64String). SeeBaseNCodecfor guidance on comparing encoded values.- Parameters:
base64String- String containing Base64 data.- Returns:
- New array containing decoded data.
- Throws:
IllegalArgumentException- Thrown when a problem is detected processing data.- Since:
- 1.4
-
decodeBase64Standard
public static byte[] decodeBase64Standard(byte[] base64Data) Decodes standard Base64 data into octets using lenient decoding.This method uses the standard alphabet. It skips unsupported input, discards data after the first padding character, and accepts noncanonical padding and trailing bits. Different encoded inputs can therefore produce the same decoded bytes. This method does not validate canonical input.
For canonical decoding, use
Base64.builder().setDecodingPolicy(CodecPolicy.STRICT).get().decode(base64Data). SeeBaseNCodecfor guidance on comparing encoded values.- Parameters:
base64Data- Byte array containing Base64 data.- Returns:
- New array containing decoded data.
- Throws:
IllegalArgumentException- Thrown when a problem is detected processing data.- Since:
- 1.21
-
decodeBase64Standard
Decodes a standard Base64 string into octets using lenient decoding.This method uses the standard alphabet. It skips unsupported input, discards data after the first padding character, and accepts noncanonical padding and trailing bits. Different encoded inputs can therefore produce the same decoded bytes. This method does not validate canonical input.
For canonical decoding, use
Base64.builder().setDecodingPolicy(CodecPolicy.STRICT).get().decode(base64String). SeeBaseNCodecfor guidance on comparing encoded values.- Parameters:
base64String- String containing Base64 data.- Returns:
- New array containing decoded data.
- Throws:
IllegalArgumentException- Thrown when a problem is detected processing data.- Since:
- 1.21
-
decodeBase64UrlSafe
public static byte[] decodeBase64UrlSafe(byte[] base64Data) Decodes URL-safe Base64 data into octets using lenient decoding.This method uses the URL-safe alphabet. It skips unsupported input, discards data after the first padding character, and accepts noncanonical padding and trailing bits. Different encoded inputs can therefore produce the same decoded bytes. This method does not validate canonical input.
For canonical decoding, use
Base64.builder().setUrlSafe(true).setDecodingPolicy(CodecPolicy.STRICT).get().decode(base64Data). SeeBaseNCodecfor guidance on comparing encoded values.- Parameters:
base64Data- Byte array containing Base64 data.- Returns:
- New array containing decoded data.
- Throws:
IllegalArgumentException- Thrown when a problem is detected processing data.- Since:
- 1.21
-
decodeBase64UrlSafe
Decodes a URL-safe Base64 string into octets using lenient decoding.This method uses the URL-safe alphabet. It skips unsupported input, discards data after the first padding character, and accepts noncanonical padding and trailing bits. Different encoded inputs can therefore produce the same decoded bytes. This method does not validate canonical input.
For canonical decoding, use
Base64.builder().setUrlSafe(true).setDecodingPolicy(CodecPolicy.STRICT).get().decode(base64String). SeeBaseNCodecfor guidance on comparing encoded values.- Parameters:
base64String- String containing Base64 data.- Returns:
- New array containing decoded data.
- Throws:
IllegalArgumentException- Thrown when a problem is detected processing data.- Since:
- 1.21
-
decodeInteger
Decodes a byte64-encoded integer according to crypto standards such as W3C's XML-Signature.- Parameters:
array- A byte array containing base64 character data.- Returns:
- A BigInteger.
- Throws:
IllegalArgumentException- Thrown when a problem is detected processing data.- Since:
- 1.4
-
encodeBase64
public static byte[] encodeBase64(byte[] binaryData) Encodes binary data using the base64 algorithm but does not chunk the output.- Parameters:
binaryData- binary data to encode.- Returns:
- byte[] containing Base64 characters in their UTF-8 representation.
-
encodeBase64
public static byte[] encodeBase64(byte[] binaryData, boolean isChunked) Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks.- Parameters:
binaryData- Array containing binary data to encode.isChunked- iftruethis encoder will chunk the base64 output into 76 character blocks.- Returns:
- Base64-encoded data.
- Throws:
IllegalArgumentException- Thrown when the input array needs an output array bigger thanInteger.MAX_VALUE.
-
encodeBase64
public static byte[] encodeBase64(byte[] binaryData, boolean isChunked, boolean urlSafe) Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks.- Parameters:
binaryData- Array containing binary data to encode.isChunked- iftruethis encoder will chunk the base64 output into 76 character blocks.urlSafe- iftruethis encoder will emit - and _ instead of the usual + and / characters. No padding is added when encoding using the URL-safe alphabet.- Returns:
- Base64-encoded data.
- Throws:
IllegalArgumentException- Thrown when the input array needs an output array bigger thanInteger.MAX_VALUE.- Since:
- 1.4
-
encodeBase64
public static byte[] encodeBase64(byte[] binaryData, boolean isChunked, boolean urlSafe, int maxResultSize) Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks.- Parameters:
binaryData- Array containing binary data to encode.isChunked- iftruethis encoder will chunk the base64 output into 76 character blocks.urlSafe- iftruethis encoder will emit - and _ instead of the usual + and / characters. No padding is added when encoding using the URL-safe alphabet.maxResultSize- The maximum result size to accept.- Returns:
- Base64-encoded data.
- Throws:
IllegalArgumentException- Thrown when the input array needs an output array bigger than maxResultSize.- Since:
- 1.4
-
encodeBase64Chunked
public static byte[] encodeBase64Chunked(byte[] binaryData) Encodes binary data using the base64 algorithm and chunks the encoded output into 76 character blocks- Parameters:
binaryData- binary data to encode.- Returns:
- Base64 characters chunked in 76 character blocks.
-
encodeBase64String
Encodes binary data using the base64 algorithm but does not chunk the output.We changed the behavior of this method from multi-line chunking (1.4) to single-line non-chunking (1.5).
- Parameters:
binaryData- binary data to encode.- Returns:
- String containing Base64 characters.
- Since:
- 1.4 (NOTE: 1.4 chunked the output, whereas 1.5 does not).
-
encodeBase64URLSafe
public static byte[] encodeBase64URLSafe(byte[] binaryData) Encodes binary data using a URL-safe variation of the base64 algorithm but does not chunk the output. The url-safe variation emits - and _ instead of + and / characters. No padding is added.- Parameters:
binaryData- binary data to encode.- Returns:
- byte[] containing Base64 characters in their UTF-8 representation.
- Since:
- 1.4
-
encodeBase64URLSafeString
Encodes binary data using a URL-safe variation of the base64 algorithm but does not chunk the output. The url-safe variation emits - and _ instead of + and / characters. No padding is added.- Parameters:
binaryData- binary data to encode.- Returns:
- String containing Base64 characters.
- Since:
- 1.4
-
encodeInteger
Encodes to a byte64-encoded integer according to crypto standards such as W3C's XML-Signature.- Parameters:
bigInteger- A BigInteger.- Returns:
- A byte array containing base64 character data.
- Throws:
NullPointerException- Thrown if null is passed in.- Since:
- 1.4
-
isArrayByteBase64
Deprecated.1.5 UseisBase64(byte[]), will be removed in 2.0.Tests a given byte array to see if it contains only valid characters within the Base64 alphabet. Currently the method treats whitespace as valid.- Parameters:
arrayOctet- byte array to test.- Returns:
trueif all bytes are valid characters in the Base64 alphabet or if the byte array is empty;false, otherwise.
-
isBase64
public static boolean isBase64(byte octet) Tests whether or not theoctetis in the Base64 alphabet.This method treats all characters included within standard base64 and base64url encodings as valid base64 characters. This includes the '+' and '/' (standard base64), as well as '-' and '_' (URL-safe base64) characters. To test membership in only the standard Base64 or Base64 URL-safe alphabet, use
isBase64Standard(byte)orisBase64Url(byte)methods respectively.- Parameters:
octet- The value to test.- Returns:
trueif the value is defined in the Base64 alphabet,falseotherwise.- Since:
- 1.4
-
isBase64
public static boolean isBase64(byte[] arrayOctet) Tests a given byte array to see if it contains only valid characters within the Base64 alphabet. Currently the method treats whitespace as valid.This method treats all characters included within standard base64 and base64url encodings as valid base64 characters. This includes the '+' and '/' (standard base64), as well as '-' and '_' (URL-safe base64) characters. To test membership in only the standard Base64 or Base64 URL-safe alphabet, use
isBase64Standard(byte[])orisBase64Url(byte[])methods respectively.This is a character-membership check, not canonical validation. It permits whitespace and padding in any position and does not check trailing bits. Use an instance configured with
CodecPolicy.STRICTto require canonical input.- Parameters:
arrayOctet- byte array to test.- Returns:
trueif all bytes are valid characters in the Base64 alphabet or if the byte array is empty;false, otherwise.- Since:
- 1.5
-
isBase64
Tests a given String to see if it contains only valid characters within the Base64 alphabet. Currently the method treats whitespace as valid.This method treats all characters included within standard base64 and base64url encodings as valid base64 characters. This includes the '+' and '/' (standard base64), as well as '-' and '_' (URL-safe base64) characters. To test membership in only the standard Base64 or Base64 URL-safe alphabet, use
isBase64Standard(String)orisBase64Url(String)methods respectively.This is a character-membership check, not canonical validation. It permits whitespace and padding in any position and does not check trailing bits. Use an instance configured with
CodecPolicy.STRICTto require canonical input.- Parameters:
base64- String to test.- Returns:
trueif all characters in the String are valid characters in the Base64 alphabet or if the String is empty;false, otherwise.- Since:
- 1.5
-
isBase64Standard
public static boolean isBase64Standard(byte octet) Tests whether or not theoctetis in the standard Base64 alphabet.This implementation is aligned with RFC 2045 Table 1: The Base64 Alphabet.
- Parameters:
octet- The value to test.- Returns:
trueif the value is defined in the standard Base64 alphabet,falseotherwise.- Since:
- 1.21
-
isBase64Standard
public static boolean isBase64Standard(byte[] arrayOctet) Tests a given byte array to see if it contains only valid characters within the standard Base64 alphabet. The method treats whitespace as valid.This implementation is aligned with RFC 2045 Table 1: The Base64 Alphabet.
This is a character-membership check, not canonical validation. It permits whitespace and padding in any position and does not check trailing bits. Use an instance configured with
CodecPolicy.STRICTto require canonical input.- Parameters:
arrayOctet- byte array to test.- Returns:
trueif all bytes are valid characters in the standard Base64 alphabet.false, otherwise.- Since:
- 1.21
-
isBase64Standard
Tests a given String to see if it contains only valid characters within the standard Base64 alphabet. The method treats whitespace as valid.This implementation is aligned with RFC 2045 Table 1: The Base64 Alphabet.
This is a character-membership check, not canonical validation. It permits whitespace and padding in any position and does not check trailing bits. Use an instance configured with
CodecPolicy.STRICTto require canonical input.- Parameters:
base64- String to test.- Returns:
trueif all characters in the String are valid characters in the standard Base64 alphabet or if the String is empty;false, otherwise.- Since:
- 1.21
-
isBase64Url
public static boolean isBase64Url(byte octet) Tests whether or not theoctetis in the URL-safe Base64 alphabet.This implementation is aligned with RFC 4648 Table 2: The "URL and Filename safe" Base 64 Alphabet.
- Parameters:
octet- The value to test.- Returns:
trueif the value is defined in the URL-safe Base64 alphabet,falseotherwise.- Since:
- 1.21
-
isBase64Url
public static boolean isBase64Url(byte[] arrayOctet) Tests a given byte array to see if it contains only valid characters within the URL-safe Base64 alphabet. The method treats whitespace as valid.This implementation is aligned with RFC 4648 Table 2: The "URL and Filename safe" Base 64 Alphabet.
This is a character-membership check, not canonical validation. It permits whitespace and padding in any position and does not check trailing bits. Use an instance configured with
CodecPolicy.STRICTto require canonical input.- Parameters:
arrayOctet- byte array to test.- Returns:
trueif all bytes are valid characters in the URL-safe Base64 alphabet,false, otherwise.- Since:
- 1.21
-
isBase64Url
Tests a given String to see if it contains only valid characters within the URL-safe Base64 alphabet. The method treats whitespace as valid.This implementation is aligned with RFC 4648 Table 2: The "URL and Filename safe" Base 64 Alphabet.
This is a character-membership check, not canonical validation. It permits whitespace and padding in any position and does not check trailing bits. Use an instance configured with
CodecPolicy.STRICTto require canonical input.- Parameters:
base64- String to test.- Returns:
trueif all characters in the String are valid characters in the URL-safe Base64 alphabet or if the String is empty;false, otherwise.- Since:
- 1.21
-
toDecodeTable
private static byte[] toDecodeTable(byte[] encodeTable) -
toUrlSafeEncodeTable
static byte[] toUrlSafeEncodeTable(boolean urlSafe) -
decode
Decodes all of the provided data, starting at inPos, for inAvail bytes. Should be called at least twice: once with the data to decode, and once with inAvail set to "-1" to alert decoder that EOF has been reached. Strict decoding requires the "-1" call to validate the complete input.
Lenient decoding ignores non-alphabet characters and stops at the first padding byte. Strict decoding accepts only the canonical form produced by this instance's encoder, including its alphabet, padding, and line separators.
Thanks to "commons" project in ws.apache.org for the bitwise operations, and general approach. https://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/
- Specified by:
decodein classBaseNCodec- Parameters:
input- byte[] array of ASCII data to base64 decode.inPos- Position to start reading data from.inAvail- Amount of bytes available from input for decoding.context- The context to be used.- Throws:
IllegalArgumentException- Thrown when a problem is detected processing data.
-
encode
Encodes all of the provided data, starting at inPos, for inAvail bytes. Must be called at least twice: once with the data to encode, and once with inAvail set to "-1" to alert encoder that EOF has been reached, to flush last remaining bytes (if not multiple of 3).
No padding is added when encoding using the URL-safe alphabet.
Thanks to "commons" project in ws.apache.org for the bitwise operations, and general approach. https://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/
- Specified by:
encodein classBaseNCodec- Parameters:
in- byte[] array of binary data to base64 encode.inPos- Position to start reading data from.inAvail- Amount of bytes available from input for encoding.context- The context to be used.- Throws:
IllegalArgumentException- Thrown when a problem is detected processing data.
-
getLineSeparator
byte[] getLineSeparator()Gets the line separator (for testing only).- Returns:
- The line separator.
-
isInAlphabet
protected boolean isInAlphabet(byte octet) Tests whether theoctetis in the Base64 alphabet.- Specified by:
isInAlphabetin classBaseNCodec- Parameters:
octet- The value to test.- Returns:
trueif the value is defined in the Base64 alphabetfalseotherwise.
-
isUrlSafe
public boolean isUrlSafe()Tests whether the current encoding mode is URL-safe.- Returns:
- true if we're in URL-safe mode, false otherwise.
- Since:
- 1.4
-
validateCharacter
Validates whether decoding the final trailing character is possible in the context of the set of possible Base64 values.The character is valid if the lower bits within the provided mask are zero. This is used to test the final trailing base-64 digit is zero in the bits that will be discarded.
- Parameters:
emptyBitsMask- The mask of the lower bits that should be empty.context- The context to be used.- Throws:
IllegalArgumentException- Thrown if the bits being checked contain any non-zero value.
-
validateTrailingCharacter
private void validateTrailingCharacter()Validates whether decoding allows an entire final trailing character that cannot be used for a complete byte.- Throws:
IllegalArgumentException- Thrown if strict decoding is enabled.
-
builder()andBase64.Builder.