    001/*
    002 * Licensed to the Apache Software Foundation (ASF) under one or more
    003 * contributor license agreements.  See the NOTICE file distributed with
    004 * this work for additional information regarding copyright ownership.
    005 * The ASF licenses this file to You under the Apache License, Version 2.0
    006 * (the "License"); you may not use this file except in compliance with
    007 * the License.  You may obtain a copy of the License at
    008 *
    009 *      https://www.apache.org/licenses/LICENSE-2.0
    010 *
    011 * Unless required by applicable law or agreed to in writing, software
    012 * distributed under the License is distributed on an "AS IS" BASIS,
    013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014 * See the License for the specific language governing permissions and
    015 * limitations under the License.
    016 */
    017
    018package org.apache.commons.net.util;
    019
    020import java.math.BigInteger;
    021import java.nio.charset.StandardCharsets;
    022import java.util.Base64.Decoder;
    023import java.util.Base64.Encoder;
    024import java.util.Objects;
    025
    026/**
    027 * Provides Base64 encoding and decoding as defined by RFC 2045.
    028 *
    029 * <p>
    030 * This class implements section <cite>6.8. Base64 Content-Transfer-Encoding</cite> from RFC 2045 <cite>Multipurpose Internet Mail Extensions (MIME) Part One:
    031 * Format of Internet Message Bodies</cite> by Freed and Borenstein.
    032 * </p>
    033 * <p>
    034 * The class can be parameterized in the following manner with various constructors:
    035 * <ul>
    036 * <li>URL-safe mode: Default off.</li>
    037 * <li>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.
    038 * <li>Line separator: Default is CRLF ("\r\n")</li>
    039 * </ul>
    040 * <p>
    041 * Since this class operates directly on byte streams, and not character streams, it is hard-coded to only encode/decode character encodings which are
    042 * compatible with the lower 127 ASCII chart (ISO-8859-1, Windows-1252, UTF-8, etc).
    043 * </p>
    044 *
    045 * @deprecated Use {@link java.util.Base64}.
    046 * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>
    047 * @since 2.2
    048 */
    049@Deprecated
    050public class Base64 {
    051
    052    /**
    053     * Chunk size per RFC 2045 section 6.8.
    054     *
    055     * <p>
    056     * The {@value} character limit does not count the trailing CRLF, but counts all other characters, including any equal signs.
    057     * </p>
    058     *
    059     * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 6.8</a>
    060     */
    061    static final int CHUNK_SIZE = 76;
    062
    063    /**
    064     * Chunk separator per RFC 2045 section 2.1.
    065     *
    066     * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 2.1</a>
    067     */
    068    static final byte[] CHUNK_SEPARATOR = { '\r', '\n' };
    069
    070    /**
    071     * Byte used to pad output.
    072     */
    073    private static final byte PAD = '=';
    074
    075    /**
    076     * 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
    077     * positive integer equivalents. Characters that are not in the Base64 alphabet but fall within the bounds of the array are translated to -1.
    078     *
    079     * Note: '+' and '-' both decode to 62. '/' and '_' both decode to 63. This means decoder seamlessly handles both URL_SAFE and STANDARD base64. (The
    080     * encoder, on the other hand, needs to know ahead of time what to emit).
    081     *
    082     * Thanks to "commons" project in ws.apache.org for <a href="https://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/">this code</a>
    083     */
    084    private static final byte[] DECODE_TABLE = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    085            -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, 62, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1,
    086            0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, 63, -1, 26, 27, 28, 29, 30, 31, 32,
    087            33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51 };
    088
    089    // The static final fields above are used for the original static byte[] methods on Base64.
    090    // The private member fields below are used with the new streaming approach, which requires
    091    // some state be preserved between calls of encode() and decode().
    092
    093    /**
    094     * Tests a given byte array to see if it contains any valid character within the Base64 alphabet.
    095     *
    096     * @param arrayOctet byte array to test
    097     * @return {@code true} if any byte is a valid character in the Base64 alphabet; {@code false} otherwise
    098     */
    099    private static boolean containsBase64Byte(final byte[] arrayOctet) {
    100        for (final byte element : arrayOctet) {
    101            if (isBase64(element)) {
    102                return true;
    103            }
    104        }
    105        return false;
    106    }
    107
    108    /**
    109     * Decodes Base64 data into octets.
    110     *
    111     * @param base64 Byte array containing Base64 data
    112     * @return Array containing decoded data.
    113     */
    114    public static byte[] decodeBase64(final byte[] base64) {
    115        return isEmpty(base64) ? base64 : getDecoder().decode(base64);
    116    }
    117
    118    /**
    119     * Decodes a Base64 String into octets.
    120     *
    121     * @param base64 String containing Base64 data
    122     * @return Array containing decoded data.
    123     * @since 1.4
    124     */
    125    public static byte[] decodeBase64(final String base64) {
    126        return getDecoder().decode(base64);
    127    }
    128
    129    /**
    130     * Decodes a byte64-encoded integer according to crypto standards such as W3C's XML-Signature
    131     *
    132     * @param source a byte array containing base64 character data
    133     * @return A BigInteger
    134     * @since 1.4
    135     */
    136    public static BigInteger decodeInteger(final byte[] source) {
    137        return new BigInteger(1, decodeBase64(source));
    138    }
    139
    140    private static byte[] encode(final byte[] binaryData, final int lineLength, final byte[] lineSeparator, final boolean urlSafe) {
    141        if (isEmpty(binaryData)) {
    142            return binaryData;
    143        }
    144        return lineLength > 0 ? encodeBase64Chunked(binaryData, lineLength, lineSeparator)
    145                : urlSafe ? encodeBase64URLSafe(binaryData) : encodeBase64(binaryData);
    146    }
    147
    148    /**
    149     * Encodes binary data using the base64 algorithm but does not chunk the output.
    150     *
    151     * @param source binary data to encode
    152     * @return byte[] containing Base64 characters in their UTF-8 representation.
    153     */
    154    public static byte[] encodeBase64(final byte[] source) {
    155        return isEmpty(source) ? source : getEncoder().encode(source);
    156    }
    157
    158    /**
    159     * Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks.
    160     *
    161     * @param binaryData Array containing binary data to encode.
    162     * @param chunked  if {@code true} this encoder will chunk the base64 output into 76 character blocks
    163     * @return Base64-encoded data.
    164     * @throws IllegalArgumentException Thrown when the input array needs an output array bigger than {@link Integer#MAX_VALUE}
    165     */
    166    public static byte[] encodeBase64(final byte[] binaryData, final boolean chunked) {
    167        return chunked ? encodeBase64Chunked(binaryData) : encodeBase64(binaryData, false, false);
    168    }
    169
    170    /**
    171     * Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks.
    172     *
    173     * @param binaryData Array containing binary data to encode.
    174     * @param chunked  if {@code true} this encoder will chunk the base64 output into 76 character blocks
    175     * @param urlSafe    if {@code true} this encoder will emit - and _ instead of the usual + and / characters.
    176     * @return Base64-encoded data.
    177     * @throws IllegalArgumentException Thrown when the input array needs an output array bigger than {@link Integer#MAX_VALUE}
    178     * @since 1.4
    179     */
    180    public static byte[] encodeBase64(final byte[] binaryData, final boolean chunked, final boolean urlSafe) {
    181        return encodeBase64(binaryData, chunked, urlSafe, Integer.MAX_VALUE);
    182    }
    183
    184    /**
    185     * Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks.
    186     *
    187     * @param binaryData    Array containing binary data to encode.
    188     * @param chunked     if {@code true} this encoder will chunk the base64 output into 76 character blocks
    189     * @param urlSafe       if {@code true} this encoder will emit - and _ instead of the usual + and / characters.
    190     * @param maxResultSize The maximum result size to accept.
    191     * @return Base64-encoded data.
    192     * @throws IllegalArgumentException Thrown when the input array needs an output array bigger than maxResultSize
    193     * @since 1.4
    194     */
    195    public static byte[] encodeBase64(final byte[] binaryData, final boolean chunked, final boolean urlSafe, final int maxResultSize) {
    196        if (isEmpty(binaryData)) {
    197            return binaryData;
    198        }
    199        final long len = getEncodeLength(binaryData, chunked ? CHUNK_SIZE : 0, chunked ? CHUNK_SEPARATOR : NetConstants.EMPTY_BTYE_ARRAY);
    200        if (len > maxResultSize) {
    201            throw new IllegalArgumentException(
    202                    "Input array too big, the output array would be bigger (" + len + ") than the specified maxium size of " + maxResultSize);
    203        }
    204        return chunked ? encodeBase64Chunked(binaryData) : urlSafe ? encodeBase64URLSafe(binaryData) : encodeBase64(binaryData);
    205    }
    206
    207    /**
    208     * Encodes binary data using the base64 algorithm and chunks the encoded output into 76 character blocks separated by CR-LF.
    209     * <p>
    210     * The return value ends in a CR-LF.
    211     * </p>
    212     *
    213     * @param binaryData binary data to encode
    214     * @return Base64 characters chunked in 76 character blocks
    215     * @throws ArithmeticException if the {@code binaryData} would overflows a byte[].
    216     */
    217    public static byte[] encodeBase64Chunked(final byte[] binaryData) {
    218        return encodeBase64Chunked(binaryData, CHUNK_SIZE, CHUNK_SEPARATOR);
    219    }
    220
    221    private static byte[] encodeBase64Chunked(final byte[] binaryData, final int lineLength, final byte[] lineSeparator) {
    222        final long encodeLength = getEncodeLength(binaryData, lineLength, lineSeparator);
    223        final byte[] dst = new byte[Math.toIntExact(encodeLength)];
    224        getMimeEncoder(lineLength, lineSeparator).encode(binaryData, dst);
    225        // Copy chunk separator at the end
    226        System.arraycopy(lineSeparator, 0, dst, dst.length - lineSeparator.length, lineSeparator.length);
    227        return dst;
    228    }
    229
    230    /**
    231     * Encodes binary data using the base64 algorithm into 76 character blocks separated by CR-LF.
    232     * <p>
    233     * The return value ends in a CR-LF.
    234     * </p>
    235     * <p>
    236     * For a non-chunking version, see {@link #encodeBase64StringUnChunked(byte[])}.
    237     * </p>
    238     *
    239     * @param binaryData binary data to encode
    240     * @return String containing Base64 characters.
    241     * @since 1.4
    242     */
    243    public static String encodeBase64String(final byte[] binaryData) {
    244        return getMimeEncoder().encodeToString(binaryData) + "\r\n";
    245    }
    246
    247    /**
    248     * Encodes binary data using the base64 algorithm.
    249     *
    250     * @param binaryData  binary data to encode
    251     * @param chunked whether to split the output into chunks
    252     * @return String containing Base64 characters.
    253     * @since 3.2
    254     */
    255    public static String encodeBase64String(final byte[] binaryData, final boolean chunked) {
    256        return newStringUtf8(encodeBase64(binaryData, chunked));
    257    }
    258
    259    /**
    260     * Encodes binary data using the base64 algorithm, without using chunking.
    261     * <p>
    262     * For a chunking version, see {@link #encodeBase64String(byte[])}.
    263     * </p>
    264     *
    265     * @param binaryData binary data to encode
    266     * @return String containing Base64 characters.
    267     * @since 3.2
    268     */
    269    public static String encodeBase64StringUnChunked(final byte[] binaryData) {
    270        return getEncoder().encodeToString(binaryData);
    271    }
    272
    273    /**
    274     * 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 +
    275     * and / characters.
    276     *
    277     * @param binaryData binary data to encode
    278     * @return byte[] containing Base64 characters in their UTF-8 representation.
    279     * @since 1.4
    280     */
    281    public static byte[] encodeBase64URLSafe(final byte[] binaryData) {
    282        return getUrlEncoder().withoutPadding().encode(binaryData);
    283    }
    284
    285    /**
    286     * 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 +
    287     * and / characters.
    288     *
    289     * @param binaryData binary data to encode
    290     * @return String containing Base64 characters
    291     * @since 1.4
    292     */
    293    public static String encodeBase64URLSafeString(final byte[] binaryData) {
    294        return getUrlEncoder().withoutPadding().encodeToString(binaryData);
    295    }
    296
    297    /**
    298     * Encodes to a byte64-encoded integer according to crypto standards such as W3C's XML-Signature
    299     *
    300     * @param bigInt a BigInteger
    301     * @return A byte array containing base64 character data
    302     * @throws NullPointerException if null is passed in
    303     * @since 1.4
    304     */
    305    public static byte[] encodeInteger(final BigInteger bigInt) {
    306        return encodeBase64(toIntegerBytes(bigInt), false);
    307    }
    308
    309    private static Decoder getDecoder() {
    310        return java.util.Base64.getDecoder();
    311    }
    312
    313    /**
    314     * Pre-calculates the amount of space needed to base64-encode the supplied array.
    315     *
    316     * @param array          byte[] array which will later be encoded
    317     * @param lineSize      line-length of the output (<= 0 means no chunking) between each chunkSeparator (e.g. CRLF).
    318     * @param linkSeparator the sequence of bytes used to separate chunks of output (e.g. CRLF).
    319     * @return amount of space needed to encode the supplied array. Returns a long since a max-len array will require Integer.MAX_VALUE + 33%.
    320     */
    321    static long getEncodeLength(final byte[] array, int lineSize, final byte[] linkSeparator) {
    322        // base64 always encodes to multiples of 4.
    323        lineSize = lineSize / 4 * 4;
    324        long len = array.length * 4 / 3;
    325        final long mod = len % 4;
    326        if (mod != 0) {
    327            len += 4 - mod;
    328        }
    329        if (lineSize > 0) {
    330            final boolean lenChunksPerfectly = len % lineSize == 0;
    331            len += len / lineSize * linkSeparator.length;
    332            if (!lenChunksPerfectly) {
    333                len += linkSeparator.length;
    334            }
    335        }
    336        return len;
    337    }
    338
    339    private static Encoder getEncoder() {
    340        return java.util.Base64.getEncoder();
    341    }
    342
    343    private static Encoder getMimeEncoder() {
    344        return java.util.Base64.getMimeEncoder();
    345    }
    346
    347    private static Encoder getMimeEncoder(final int lineLength, final byte[] lineSeparator) {
    348        return java.util.Base64.getMimeEncoder(lineLength, lineSeparator);
    349    }
    350
    351    private static Encoder getUrlEncoder() {
    352        return java.util.Base64.getUrlEncoder();
    353    }
    354
    355    /**
    356     * Tests a given byte array to see if it contains only valid characters within the Base64 alphabet. Currently, the method treats whitespace as valid.
    357     *
    358     * @param arrayOctet byte array to test
    359     * @return {@code true} if all bytes are valid characters in the Base64 alphabet or if the byte array is empty; false, otherwise
    360     */
    361    public static boolean isArrayByteBase64(final byte[] arrayOctet) {
    362        for (final byte element : arrayOctet) {
    363            if (!isBase64(element) && !isWhiteSpace(element)) {
    364                return false;
    365            }
    366        }
    367        return true;
    368    }
    369
    370    /**
    371     * Tests whether or not the {@code octet} is in the base 64 alphabet.
    372     *
    373     * @param octet The value to test
    374     * @return {@code true} if the value is defined in the base 64 alphabet, {@code false} otherwise.
    375     * @since 1.4
    376     */
    377    public static boolean isBase64(final byte octet) {
    378        return octet == PAD || octet >= 0 && octet < DECODE_TABLE.length && DECODE_TABLE[octet] != -1;
    379    }
    380
    381    private static boolean isEmpty(final byte[] array) {
    382        return array == null || array.length == 0;
    383    }
    384
    385    /**
    386     * Checks if a byte value is whitespace or not.
    387     *
    388     * @param byteToCheck the byte to check
    389     * @return true if byte is whitespace, false otherwise
    390     */
    391    private static boolean isWhiteSpace(final byte byteToCheck) {
    392        switch (byteToCheck) {
    393        case ' ':
    394        case '\n':
    395        case '\r':
    396        case '\t':
    397            return true;
    398        default:
    399            return false;
    400        }
    401    }
    402
    403    private static String newStringUtf8(final byte[] encode) {
    404        return new String(encode, StandardCharsets.UTF_8);
    405    }
    406
    407    /**
    408     * Returns a byte-array representation of a {@code BigInteger} without sign bit.
    409     *
    410     * @param bigInt {@code BigInteger} to be converted
    411     * @return a byte array representation of the BigInteger parameter
    412     */
    413    private static byte[] toIntegerBytes(final BigInteger bigInt) {
    414        Objects.requireNonNull(bigInt, "bigInt");
    415        int bitlen = bigInt.bitLength();
    416        // round bitlen
    417        bitlen = bitlen + 7 >> 3 << 3;
    418        final byte[] bigBytes = bigInt.toByteArray();
    419        if (bigInt.bitLength() % 8 != 0 && bigInt.bitLength() / 8 + 1 == bitlen / 8) {
    420            return bigBytes;
    421        }
    422        // set up params for copying everything but sign bit
    423        int startSrc = 0;
    424        int len = bigBytes.length;
    425
    426        // if bigInt is exactly byte-aligned, just skip signbit in copy
    427        if (bigInt.bitLength() % 8 == 0) {
    428            startSrc = 1;
    429            len--;
    430        }
    431        final int startDst = bitlen / 8 - len; // to pad w/ nulls as per spec
    432        final byte[] resizedBytes = new byte[bitlen / 8];
    433        System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, len);
    434        return resizedBytes;
    435    }
    436
    437    /**
    438     * Line length for encoding. Not used when decoding. A value of zero or less implies no chunking of the base64 encoded data.
    439     */
    440    private final int lineLength;
    441
    442    /**
    443     * Line separator for encoding. Not used when decoding. Only used if lineLength > 0.
    444     */
    445    private final byte[] lineSeparator;
    446
    447    /**
    448     * Whether encoding is URL and filename safe, or not.
    449     */
    450    private final boolean urlSafe;
    451
    452    /**
    453     * Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.
    454     * <p>
    455     * When encoding the line length is 76, the line separator is CRLF, and the encoding table is STANDARD_ENCODE_TABLE.
    456     * </p>
    457     *
    458     * <p>
    459     * When decoding all variants are supported.
    460     * </p>
    461     */
    462    public Base64() {
    463        this(false);
    464    }
    465
    466    /**
    467     * Creates a Base64 codec used for decoding (all modes) and encoding in the given URL-safe mode.
    468     * <p>
    469     * When encoding the line length is 76, the line separator is CRLF, and the encoding table is STANDARD_ENCODE_TABLE.
    470     * </p>
    471     *
    472     * <p>
    473     * When decoding all variants are supported.
    474     * </p>
    475     *
    476     * @param urlSafe if {@code true}, URL-safe encoding is used. In most cases this should be set to {@code false}.
    477     * @since 1.4
    478     */
    479    public Base64(final boolean urlSafe) {
    480        this(CHUNK_SIZE, CHUNK_SEPARATOR, urlSafe);
    481    }
    482
    483    /**
    484     * Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.
    485     * <p>
    486     * When encoding the line length is given in the constructor, the line separator is CRLF, and the encoding table is STANDARD_ENCODE_TABLE.
    487     * </p>
    488     * <p>
    489     * Line lengths that aren't multiples of 4 will still essentially end up being multiples of 4 in the encoded data.
    490     * </p>
    491     * <p>
    492     * When decoding all variants are supported.
    493     * </p>
    494     *
    495     * @param lineLength Each line of encoded data will be at most of the given length (rounded down to the nearest multiple of 4).
    496     *                   If {@code lineLength <= 0}, then the output will not be divided into lines (chunks). Ignored when decoding.
    497     * @since 1.4
    498     */
    499    public Base64(final int lineLength) {
    500        this(lineLength, CHUNK_SEPARATOR);
    501    }
    502
    503    /**
    504     * Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.
    505     * <p>
    506     * When encoding the line length and line separator are given in the constructor, and the encoding table is STANDARD_ENCODE_TABLE.
    507     * </p>
    508     * <p>
    509     * Line lengths that aren't multiples of 4 will still essentially end up being multiples of 4 in the encoded data.
    510     * </p>
    511     * <p>
    512     * When decoding all variants are supported.
    513     * </p>
    514     *
    515     * @param lineLength    Each line of encoded data will be at most of the given length (rounded down to the nearest multiple of 4).
    516     *                      If {@code lineLength <= 0}, then the output will not be divided into lines (chunks). Ignored when decoding.
    517     * @param lineSeparator Each line of encoded data will end with this sequence of bytes. Not used for decoding.
    518     * @throws IllegalArgumentException Thrown when the provided lineSeparator included some base64 characters.
    519     * @since 1.4
    520     */
    521    public Base64(final int lineLength, final byte[] lineSeparator) {
    522        this(lineLength, lineSeparator, false);
    523    }
    524
    525    /**
    526     * Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.
    527     * <p>
    528     * When encoding the line length and line separator are given in the constructor, and the encoding table is STANDARD_ENCODE_TABLE.
    529     * </p>
    530     * <p>
    531     * Line lengths that aren't multiples of 4 will still essentially end up being multiples of 4 in the encoded data.
    532     * </p>
    533     * <p>
    534     * When decoding all variants are supported.
    535     * </p>
    536     *
    537     * @param lineLength    Each line of encoded data will be at most of the given length (rounded down to the nearest multiple of 4).
    538     *                      If {@code lineLength <= 0}, then the output will not be divided into lines (chunks). Ignored when decoding.
    539     * @param lineSeparator Each line of encoded data will end with this sequence of bytes. Not used for decoding.
    540     * @param urlSafe       Instead of emitting '+' and '/' we emit '-' and '_' respectively. urlSafe is only applied to encode operations. Decoding seamlessly
    541     *                      handles both modes.
    542     * @throws IllegalArgumentException The provided lineSeparator included some base64 characters. That's not going to work!
    543     * @since 1.4
    544     */
    545    public Base64(int lineLength, byte[] lineSeparator, final boolean urlSafe) {
    546        if (lineSeparator == null || urlSafe) {
    547            lineLength = 0; // disable chunk-separating
    548            lineSeparator = NetConstants.EMPTY_BTYE_ARRAY; // this just gets ignored
    549        }
    550        this.lineLength = lineLength > 0 ? lineLength / 4 * 4 : 0;
    551        this.lineSeparator = new byte[lineSeparator.length];
    552        System.arraycopy(lineSeparator, 0, this.lineSeparator, 0, lineSeparator.length);
    553        if (containsBase64Byte(lineSeparator)) {
    554            final String sep = newStringUtf8(lineSeparator);
    555            throw new IllegalArgumentException("lineSeperator must not contain base64 characters: [" + sep + "]");
    556        }
    557        this.urlSafe = urlSafe;
    558    }
    559
    560    /**
    561     * Decodes a byte array containing characters in the Base64 alphabet.
    562     *
    563     * @param source A byte array containing Base64 character data
    564     * @return a byte array containing binary data; will return {@code null} if provided byte array is {@code null}.
    565     */
    566    public byte[] decode(final byte[] source) {
    567        return isEmpty(source) ? source : getDecoder().decode(source);
    568    }
    569
    570    /**
    571     * Decodes a String containing characters in the Base64 alphabet.
    572     *
    573     * @param source A String containing Base64 character data, must not be {@code null}
    574     * @return a byte array containing binary data
    575     * @since 1.4
    576     */
    577    public byte[] decode(final String source) {
    578        return getDecoder().decode(source);
    579    }
    580
    581    /**
    582     * Encodes a byte[] containing binary data, into a byte[] containing characters in the Base64 alphabet.
    583     *
    584     * @param source a byte array containing binary data
    585     * @return A byte array containing only Base64 character data
    586     */
    587    public byte[] encode(final byte[] source) {
    588        return encode(source, lineLength, lineSeparator, isUrlSafe());
    589    }
    590
    591    /**
    592     * Encodes a byte[] containing binary data, into a String containing characters in the Base64 alphabet.
    593     *
    594     * @param source a byte array containing binary data
    595     * @return A String containing only Base64 character data
    596     * @since 1.4
    597     */
    598    public String encodeToString(final byte[] source) {
    599        return newStringUtf8(encode(source));
    600    }
    601
    602    @Override
    603    public final void finalize() throws Throwable {
    604        // CT: Be wary of letting constructors throw exceptions. (CT_CONSTRUCTOR_THROW)
    605        super.finalize();
    606    }
    607
    608    int getLineLength() {
    609        return lineLength;
    610    }
    611
    612    byte[] getLineSeparator() {
    613        return lineSeparator.clone();
    614    }
    615
    616    /**
    617     * Tests whether our current encoding mode. True if we're URL-SAFE, false otherwise.
    618     *
    619     * @return true if we're in URL-SAFE mode, false otherwise.
    620     * @since 1.4
    621     */
    622    public boolean isUrlSafe() {
    623        return urlSafe;
    624    }
    625}