Top Description Fields Constructors Methods
org.apache.tomcat.util.codec.binary

public Class Base64

extends BaseNCodec
Class Inheritance

Provides Base64 encoding and decoding as defined by RFC 2045.

This class implements section 6.8. Base64 Content-Transfer-Encoding from RFC 2045 Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies by Freed and Borenstein.

The class can be parameterized in the following manner with various constructors:

The URL-safe parameter is only applied to encode operations. Decoding seamlessly handles both modes.

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.

Since
1.0
See Also
RFC 2045

Field Summary

Modifier and TypeField and Description
private static final int
BITS_PER_ENCODED_BYTE

BASE32 characters are 6 bits in length.

private static final int
private static final int
private final int
decodeSize

Convenience variable to help us determine when our buffer is going to run out of room and needs resizing.

private final byte[]
private final int
encodeSize

Convenience variable to help us determine when our buffer is going to run out of room and needs resizing.

private final byte[]
encodeTable

Encode table to use: either STANDARD or URL_SAFE.

private final byte[]
lineSeparator

Line separator for encoding.

private static final int
MASK_2BITS

Mask used to extract 2 bits, used when decoding final trailing character.

private static final int
MASK_4BITS

Mask used to extract 4 bits, used when decoding final trailing character.

private static final int
MASK_6BITS

Mask used to extract 6 bits, used when encoding

private static final byte[]
STANDARD_DECODE_TABLE

This array is a lookup table that translates Unicode characters drawn from the "Base64 Alphabet" (as specified in Table 1 of RFC 2045) into their 6-bit positive integer equivalents.

private static final byte[]
STANDARD_ENCODE_TABLE

This array is a lookup table that translates 6-bit positive integer index values into their "Base64 Alphabet" equivalents as specified in Table 1 of RFC 2045.

private static final byte[]
private static final byte[]
URL_SAFE_ENCODE_TABLE

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.

Inherited from org.apache.tomcat.util.codec.binary.BaseNCodec:
CHUNK_SEPARATOREOFlineLengthMASK_8BITSMIME_CHUNK_SIZEpadPAD_DEFAULTsm

Constructor Summary

AccessConstructor and Description
public
Base64()

Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.

public
Base64(final boolean
if true, URL-safe encoding is used. In most cases this should be set to false.
urlSafe
)

Creates a Base64 codec used for decoding (all modes) and encoding in the given URL-safe mode.

public
Base64(final int
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.
lineLength
)

Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.

public
Base64(final int
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.
lineLength
,
final byte[]
Each line of encoded data will end with this sequence of bytes.
lineSeparator
)

Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.

public
Base64(final int
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.
lineLength
,
final byte[]
Each line of encoded data will end with this sequence of bytes.
lineSeparator
,
final boolean
Instead of emitting '+' and '/' we emit '-' and '_' respectively. urlSafe is only applied to encode operations. Decoding seamlessly handles both modes.

Note

no padding is added when using the URL-safe alphabet.

urlSafe
)

Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.

Method Summary

Modifier and TypeMethod and Description
pack-priv void
decode(final byte[]
byte[] array of ASCII data to base64 decode.
input
,
int
Position to start reading data from.
inPos
,
final int
Amount of bytes available from input for decoding.
inAvail
,
final BaseNCodec.Context
the context to be used
context
)

Implements abstract org.apache.tomcat.util.codec.binary.BaseNCodec.decode.

Decodes all of the provided data, starting at inPos, for inAvail bytes.

public static byte[]
decodeBase64(final byte[] base64Data, final int off, final int len)

public static byte[]

Returns:

Array containing decoded data.
decodeBase64
(final String
String containing Base64 data
base64String
)

Decodes a Base64 String into octets.

public static byte[]
decodeBase64URLSafe(final String base64String)

pack-priv void
encode(final byte[]
byte[] array of binary data to base64 encode.
in
,
int
Position to start reading data from.
inPos
,
final int
Amount of bytes available from input for encoding.
inAvail
,
final BaseNCodec.Context
the context to be used
context
)

Implements abstract org.apache.tomcat.util.codec.binary.BaseNCodec.encode.

Encodes all of the provided data, starting at inPos, for inAvail bytes.

public static byte[]

Returns:

Base64-encoded data.
encodeBase64
(final byte[]
Array containing binary data to encode.
binaryData
,
final boolean
if true this encoder will chunk the base64 output into 76 character blocks
isChunked
)

Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks.

public static byte[]

Returns:

Base64-encoded data.
encodeBase64
(final byte[]
Array containing binary data to encode.
binaryData
,
final boolean
if true this encoder will chunk the base64 output into 76 character blocks
isChunked
,
final boolean
if true this encoder will emit - and _ instead of the usual + and / characters.

Note

no padding is added when encoding using the URL-safe alphabet.

urlSafe
)

Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks.

public static byte[]

Returns:

Base64-encoded data.
encodeBase64
(final byte[]
Array containing binary data to encode.
binaryData
,
final boolean
if true this encoder will chunk the base64 output into 76 character blocks
isChunked
,
final boolean
if true this encoder will emit - and _ instead of the usual + and / characters.

Note

no padding is added when encoding using the URL-safe alphabet.

urlSafe
,
final int
The maximum result size to accept.
maxResultSize
)

Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks.

public static String

Returns:

String containing Base64 characters.
encodeBase64String
(final byte[]
binary data to encode
binaryData
)

Encodes binary data using the base64 algorithm but does not chunk the output.

public static String

Returns:

String containing Base64 characters
encodeBase64URLSafeString
(final byte[]
binary data to encode
binaryData
)

Encodes binary data using a URL-safe variation of the base64 algorithm but does not chunk the output.

public static boolean
isInAlphabet(char c)

protected boolean

Returns:

true if the value is defined in the Base64 alphabet false otherwise.
isInAlphabet
(final byte
The value to test
octet
)

Implements abstract org.apache.tomcat.util.codec.binary.BaseNCodec.isInAlphabet.

Returns whether or not the octet is in the Base64 alphabet.

public boolean

Returns:

true if we're in URL-SAFE mode, false otherwise.
isUrlSafe
()

Returns our current encode mode.

private static void
validateCharacter(final int
The mask of the lower bits that should be empty
emptyBitsMask
,
final BaseNCodec.Context
the context to be used
context
)

Validates whether decoding the final trailing character is possible in the context of the set of possible base 64 values.

Inherited from org.apache.tomcat.util.codec.binary.BaseNCodec:
availablecontainsAlphabetOrPaddecodedecodedecodeencodeencodeencodeAsStringensureBufferSizegetDefaultBufferSizegetEncodedLengthhasDatareadResults

Field Detail

BITS_PER_ENCODED_BYTEback to summary
private static final int BITS_PER_ENCODED_BYTE

BASE32 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.

BYTES_PER_ENCODED_BLOCKback to summary
private static final int BYTES_PER_ENCODED_BLOCK
BYTES_PER_UNENCODED_BLOCKback to summary
private static final int BYTES_PER_UNENCODED_BLOCK
decodeSizeback to summary
private final int decodeSize

Convenience variable to help us determine when our buffer is going to run out of room and needs resizing. decodeSize = 3 + lineSeparator.length;

decodeTableback to summary
private final byte[] decodeTable
encodeSizeback to summary
private final int encodeSize

Convenience variable to help us determine when our buffer is going to run out of room and needs resizing. encodeSize = 4 + lineSeparator.length;

encodeTableback to summary
private final byte[] encodeTable

Encode table to use: either STANDARD or URL_SAFE.

Note

the DECODE_TABLE above remains static because it is able to decode both STANDARD and URL_SAFE streams, but the encodeTable must be a member variable so we can switch between the two modes.

lineSeparatorback to summary
private final byte[] lineSeparator

Line separator for encoding. Not used when decoding. Only used if lineLength > 0.

MASK_2BITSback to summary
private static final int MASK_2BITS

Mask used to extract 2 bits, used when decoding final trailing character.

MASK_4BITSback to summary
private static final int MASK_4BITS

Mask used to extract 4 bits, used when decoding final trailing character.

MASK_6BITSback to summary
private static final int MASK_6BITS

Mask used to extract 6 bits, used when encoding

STANDARD_DECODE_TABLEback to summary
private static final byte[] STANDARD_DECODE_TABLE

This array is a lookup table that translates Unicode characters drawn from the "Base64 Alphabet" (as specified in Table 1 of RFC 2045) 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.

Note

'+' 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_ENCODE_TABLEback to summary
private static final byte[] STANDARD_ENCODE_TABLE

This array is a lookup table that translates 6-bit positive integer index values into their "Base64 Alphabet" equivalents as specified in Table 1 of RFC 2045. Thanks to "commons" project in ws.apache.org for this code. https://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/

URL_SAFE_DECODE_TABLEback to summary
private static final byte[] URL_SAFE_DECODE_TABLE
URL_SAFE_ENCODE_TABLEback to summary
private static final byte[] URL_SAFE_ENCODE_TABLE

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. This table is only used when the Base64's mode is set to URL-SAFE.

Constructor Detail

Base64back to summary
public Base64()

Creates 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 all variants are supported.

Base64back to summary
public Base64(final boolean urlSafe)

Creates 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 all variants are supported.

Parameters
urlSafe:boolean

if true, URL-safe encoding is used. In most cases this should be set to false.

Since
1.4
Base64back to summary
public Base64(final int lineLength)

Creates 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 all variants are supported.

Parameters
lineLength:int

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.

Since
1.4
Base64back to summary
public Base64(final int lineLength, final byte[] lineSeparator)

Creates 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 all variants are supported.

Parameters
lineLength:int

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.

lineSeparator:byte[]

Each line of encoded data will end with this sequence of bytes.

Exceptions
IllegalArgumentException:
Thrown when the provided lineSeparator included some base64 characters.
Since
1.4
Base64back to summary
public Base64(final int lineLength, final byte[] lineSeparator, final boolean urlSafe)

Creates 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 all variants are supported.

Parameters
lineLength:int

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.

lineSeparator:byte[]

Each line of encoded data will end with this sequence of bytes.

urlSafe:boolean

Instead of emitting '+' and '/' we emit '-' and '_' respectively. urlSafe is only applied to encode operations. Decoding seamlessly handles both modes.

Note

no padding is added when using the URL-safe alphabet.

Exceptions
IllegalArgumentException:
Thrown when the lineSeparator contains Base64 characters.
Since
1.4

Method Detail

decodeback to summary
pack-priv void decode(final byte[] input, int inPos, final int inAvail, final BaseNCodec.Context context)

Implements abstract org.apache.tomcat.util.codec.binary.BaseNCodec.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. The "-1" call is not necessary when decoding, but it doesn't hurt, either.

Ignores all non-base64 characters. This is how chunked (e.g. 76 character) data is handled, since CR and LF are silently ignored, but has implications for other bytes, too. This method subscribes to the garbage-in, garbage-out philosophy: it will not check the provided data for validity.

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/

Parameters
input:byte[]

byte[] array of ASCII data to base64 decode.

inPos:int

Position to start reading data from.

inAvail:int

Amount of bytes available from input for decoding.

context:BaseNCodec.Context

the context to be used

Annotations
@Override
decodeBase64back to summary
public static byte[] decodeBase64(final byte[] base64Data, final int off, final int len)
decodeBase64back to summary
public static byte[] decodeBase64(final String base64String)

Decodes a Base64 String into octets.

Note

this method seamlessly handles data encoded in URL-safe or normal mode.

Parameters
base64String:String

String containing Base64 data

Returns:byte[]

Array containing decoded data.

Since
1.4
decodeBase64URLSafeback to summary
public static byte[] decodeBase64URLSafe(final String base64String)
encodeback to summary
pack-priv void encode(final byte[] in, int inPos, final int inAvail, final BaseNCodec.Context context)

Implements abstract org.apache.tomcat.util.codec.binary.BaseNCodec.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).

Note

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/

Parameters
in:byte[]

byte[] array of binary data to base64 encode.

inPos:int

Position to start reading data from.

inAvail:int

Amount of bytes available from input for encoding.

context:BaseNCodec.Context

the context to be used

Annotations
@Override
encodeBase64back to summary
public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked)

Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks.

Parameters
binaryData:byte[]

Array containing binary data to encode.

isChunked:boolean

if true this encoder will chunk the base64 output into 76 character blocks

Returns:byte[]

Base64-encoded data.

Exceptions
IllegalArgumentException:
Thrown when the input array needs an output array bigger than Integer#MAX_VALUE
encodeBase64back to summary
public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe)

Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks.

Parameters
binaryData:byte[]

Array containing binary data to encode.

isChunked:boolean

if true this encoder will chunk the base64 output into 76 character blocks

urlSafe:boolean

if true this encoder will emit - and _ instead of the usual + and / characters.

Note

no padding is added when encoding using the URL-safe alphabet.

Returns:byte[]

Base64-encoded data.

Exceptions
IllegalArgumentException:
Thrown when the input array needs an output array bigger than Integer#MAX_VALUE
Since
1.4
encodeBase64back to summary
public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe, final int maxResultSize)

Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks.

Parameters
binaryData:byte[]

Array containing binary data to encode.

isChunked:boolean

if true this encoder will chunk the base64 output into 76 character blocks

urlSafe:boolean

if true this encoder will emit - and _ instead of the usual + and / characters.

Note

no padding is added when encoding using the URL-safe alphabet.

maxResultSize:int

The maximum result size to accept.

Returns:byte[]

Base64-encoded data.

Exceptions
IllegalArgumentException:
Thrown when the input array needs an output array bigger than maxResultSize
Since
1.4
encodeBase64Stringback to summary
public static String encodeBase64String(final byte[] binaryData)

Encodes binary data using the base64 algorithm but does not chunk the output.

Note

We changed the behavior of this method from multi-line chunking (commons-codec-1.4) to single-line non-chunking (commons-codec-1.5).

Parameters
binaryData:byte[]

binary data to encode

Returns:String

String containing Base64 characters.

Since
1.4 (NOTE: 1.4 chunked the output, whereas 1.5 does not).
encodeBase64URLSafeStringback to summary
public static String encodeBase64URLSafeString(final 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.

Note

no padding is added.

Parameters
binaryData:byte[]

binary data to encode

Returns:String

String containing Base64 characters

Since
1.4
isInAlphabetback to summary
public static boolean isInAlphabet(char c)
isInAlphabetback to summary
protected boolean isInAlphabet(final byte octet)

Implements abstract org.apache.tomcat.util.codec.binary.BaseNCodec.isInAlphabet.

Returns whether or not the octet is in the Base64 alphabet.

Parameters
octet:byte

The value to test

Returns:boolean

true if the value is defined in the Base64 alphabet false otherwise.

Annotations
@Override
isUrlSafeback to summary
public boolean isUrlSafe()

Returns our current encode mode. True if we're URL-SAFE, false otherwise.

Returns:boolean

true if we're in URL-SAFE mode, false otherwise.

Since
1.4
validateCharacterback to summary
private static void validateCharacter(final int emptyBitsMask, final BaseNCodec.Context context)

Validates whether decoding the final trailing character is possible in the context of the set of possible base 64 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:int

The mask of the lower bits that should be empty

context:BaseNCodec.Context

the context to be used

Exceptions
IllegalArgumentException:
if the bits being checked contain any non-zero value