Class Base64

java.lang.Object
org.apache.commons.codec.binary.BaseNCodec
org.apache.commons.codec.binary.Base64
All Implemented Interfaces:
BinaryDecoder, BinaryEncoder, Decoder, Encoder

public class Base64 extends BaseNCodec
Provides Base64 encoding and decoding as defined by RFC 2045 Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies and portions of RFC 4648 The Base16, Base32, and Base64 Data Encodings

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 is only applied to encode operations. Decoding seamlessly handles both modes, 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()
Since:
1.0
See Also:
  • 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 all variants are supported.

    • Base64

      @Deprecated public Base64(boolean urlSafe)
      Deprecated.
      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 all variants are supported.

      Parameters:
      urlSafe - if true, URL-safe encoding is used. In most cases this should be set to false.
      Since:
      1.4
    • Base64

      @Deprecated public Base64(int lineLength)
      Deprecated.
      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 all variants are supported.

      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.
      Since:
      1.4
    • Base64

      @Deprecated public Base64(int lineLength, byte[] lineSeparator)
      Deprecated.
      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 all variants are supported.

      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.
      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 public Base64(int lineLength, byte[] lineSeparator, boolean urlSafe)
      Deprecated.
      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 all variants are supported.

      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.
      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 the lineSeparator contains Base64 characters.
      Since:
      1.4
    • Base64

      @Deprecated public Base64(int lineLength, byte[] lineSeparator, boolean urlSafe, CodecPolicy decodingPolicy)
      Deprecated.
      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 all variants are supported.

      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.
      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.
      decodingPolicy - The decoding policy.
      Throws:
      IllegalArgumentException - Thrown when the lineSeparator contains Base64 characters.
      Since:
      1.15
  • Method Details

    • builder

      public static Base64.Builder 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
    • decodeBase64

      public static byte[] decodeBase64(byte[] base64Data)
      Decodes Base64 data into octets.

      This method seamlessly handles data encoded in URL-safe or normal mode. For enforcing verification against strict standard Base64 or Base64 URL-safe tables, please use decodeBase64Standard(byte[]) or decodeBase64UrlSafe(byte[]) methods respectively. This method skips unknown or unsupported bytes.

      Parameters:
      base64Data - Byte array containing Base64 data.
      Returns:
      New array containing decoded data.
    • decodeBase64

      public static byte[] decodeBase64(String base64String)
      Decodes a Base64 String into octets.

      This method seamlessly handles data encoded in URL-safe or normal mode. For enforcing verification against strict standard Base64 or Base64 URL-safe tables, please use decodeBase64Standard(String) or decodeBase64UrlSafe(String) methods respectively. This method skips unknown or unsupported bytes.

      Parameters:
      base64String - String containing Base64 data.
      Returns:
      New array containing decoded data.
      Since:
      1.4
    • decodeBase64Standard

      public static byte[] decodeBase64Standard(byte[] base64Data)
      Decodes standard Base64 data into octets.

      This implementation is aligned with the RFC 2045 Table 1: The Base64 Alphabet. This method skips unknown or unsupported bytes.

      Parameters:
      base64Data - Byte array containing Base64 data.
      Returns:
      New array containing decoded data.
      Since:
      1.21
    • decodeBase64Standard

      public static byte[] decodeBase64Standard(String base64String)
      Decodes a standard Base64 String into octets.

      This implementation is aligned with the RFC 2045 Table 1: The Base64 Alphabet. This method skips unknown or unsupported characters.

      Parameters:
      base64String - String containing Base64 data.
      Returns:
      New array containing decoded data.
      Since:
      1.21
    • decodeBase64UrlSafe

      public static byte[] decodeBase64UrlSafe(byte[] base64Data)
      Decodes URL-safe Base64 data into octets.

      This implementation is aligned with RFC 4648 Table 2: The "URL and Filename safe" Base 64 Alphabet. This method skips unknown or unsupported characters.

      Parameters:
      base64Data - Byte array containing Base64 data.
      Returns:
      New array containing decoded data.
      Since:
      1.21
    • decodeBase64UrlSafe

      public static byte[] decodeBase64UrlSafe(String base64String)
      Decodes a URL-safe Base64 String into octets.

      This implementation is aligned with RFC 4648 Table 2: The "URL and Filename safe" Base 64 Alphabet. This method skips unknown or unsupported characters.

      Parameters:
      base64String - String containing Base64 data.
      Returns:
      New array containing decoded data.
      Since:
      1.21
    • decodeInteger

      public static BigInteger decodeInteger(byte[] array)
      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.
      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 - if true this 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 than Integer.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 - if true this encoder will chunk the base64 output into 76 character blocks.
      urlSafe - if true this 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 than Integer.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 - if true this encoder will chunk the base64 output into 76 character blocks.
      urlSafe - if true this 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

      public static String encodeBase64String(byte[] binaryData)
      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

      public static String encodeBase64URLSafeString(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:
      String containing Base64 characters.
      Since:
      1.4
    • encodeInteger

      public static byte[] encodeInteger(BigInteger bigInteger)
      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 - if null is passed in.
      Since:
      1.4
    • isArrayByteBase64

      @Deprecated public static boolean isArrayByteBase64(byte[] arrayOctet)
      Deprecated.
      1.5 Use isBase64(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:
      true if 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 the octet is in the Base64 alphabet.

      This method threats 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. For enforcing verification against strict standard Base64 or Base64 URL-safe tables, please use isBase64Standard(byte) or isBase64Url(byte) methods respectively.

      Parameters:
      octet - The value to test.
      Returns:
      true if the value is defined in the Base64 alphabet, false otherwise.
      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. For enforcing verification against strict standard Base64 or Base64 URL-safe tables, please use isBase64Standard(byte[]) or isBase64Url(byte[]) methods respectively.

      Parameters:
      arrayOctet - byte array to test.
      Returns:
      true if all bytes are valid characters in the Base64 alphabet or if the byte array is empty; false, otherwise.
      Since:
      1.5
    • isBase64

      public static boolean isBase64(String base64)
      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 threats 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. For enforcing verification against strict standard Base64 or Base64 URL-safe tables, please use isBase64Standard(String) or isBase64Url(String) methods respectively.

      Parameters:
      base64 - String to test.
      Returns:
      true if 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 the octet is in the standard Base64 alphabet.

      This implementation is aligned with RFC 2045 Table 1: The Base64 Alphabet.

      Parameters:
      octet - The value to test.
      Returns:
      true if the value is defined in the standard Base64 alphabet, false otherwise.
      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.

      Parameters:
      arrayOctet - byte array to test.
      Returns:
      true if all bytes are valid characters in the standard Base64 alphabet. false, otherwise.
      Since:
      1.21
    • isBase64Standard

      public static boolean isBase64Standard(String base64)
      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.

      Parameters:
      base64 - String to test.
      Returns:
      true if 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 the octet is 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:
      true if the value is defined in the URL-safe Base64 alphabet, false otherwise.
      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.

      Parameters:
      arrayOctet - byte array to test.
      Returns:
      true if all bytes are valid characters in the URL-safe Base64 alphabet, false, otherwise.
      Since:
      1.21
    • isBase64Url

      public static boolean isBase64Url(String base64)
      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.

      Parameters:
      base64 - String to test.
      Returns:
      true if 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
    • isInAlphabet

      protected boolean isInAlphabet(byte octet)
      Returns whether or not the octet is in the Base64 alphabet.
      Specified by:
      isInAlphabet in class BaseNCodec
      Parameters:
      octet - The value to test.
      Returns:
      true if the value is defined in the Base64 alphabet false otherwise.
    • isUrlSafe

      public boolean isUrlSafe()
      Returns our current encode mode. True if we're URL-safe, false otherwise.
      Returns:
      true if we're in URL-safe mode, false otherwise.
      Since:
      1.4