    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 *      http://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.codec.binary;
    019
    020import java.math.BigInteger;
    021
    022/**
    023 * Provides Base64 encoding and decoding as defined by <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>.
    024 *
    025 * <p>
    026 * This class implements section <cite>6.8. Base64 Content-Transfer-Encoding</cite> from RFC 2045 <cite>Multipurpose
    027 * Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies</cite> by Freed and Borenstein.
    028 * </p>
    029 * <p>
    030 * The class can be parameterized in the following manner with various constructors:
    031 * </p>
    032 * <ul>
    033 * <li>URL-safe mode: Default off.</li>
    034 * <li>Line length: Default 76. Line length that aren't multiples of 4 will still essentially end up being multiples of
    035 * 4 in the encoded data.
    036 * <li>Line separator: Default is CRLF ("\r\n")</li>
    037 * </ul>
    038 * <p>
    039 * The URL-safe parameter is only applied to encode operations. Decoding seamlessly handles both modes.
    040 * </p>
    041 * <p>
    042 * Since this class operates directly on byte streams, and not character streams, it is hard-coded to only
    043 * encode/decode character encodings which are compatible with the lower 127 ASCII chart (ISO-8859-1, Windows-1252,
    044 * UTF-8, etc).
    045 * </p>
    046 * <p>
    047 * This class is thread-safe.
    048 * </p>
    049 *
    050 * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>
    051 * @since 1.0
    052 */
    053public class Base64 extends BaseNCodec {
    054
    055    /**
    056     * BASE32 characters are 6 bits in length.
    057     * They are formed by taking a block of 3 octets to form a 24-bit string,
    058     * which is converted into 4 BASE64 characters.
    059     */
    060    private static final int BITS_PER_ENCODED_BYTE = 6;
    061    private static final int BYTES_PER_UNENCODED_BLOCK = 3;
    062    private static final int BYTES_PER_ENCODED_BLOCK = 4;
    063
    064    /**
    065     * Chunk separator per RFC 2045 section 2.1.
    066     *
    067     * <p>
    068     * N.B. The next major release may break compatibility and make this field private.
    069     * </p>
    070     *
    071     * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 2.1</a>
    072     */
    073    static final byte[] CHUNK_SEPARATOR = {'\r', '\n'};
    074
    075    /**
    076     * This array is a lookup table that translates 6-bit positive integer index values into their "Base64 Alphabet"
    077     * equivalents as specified in Table 1 of RFC 2045.
    078     *
    079     * Thanks to "commons" project in ws.apache.org for this code.
    080     * http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/
    081     */
    082    private static final byte[] STANDARD_ENCODE_TABLE = {
    083            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
    084            'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
    085            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
    086            'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
    087            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
    088    };
    089
    090    /**
    091     * This is a copy of the STANDARD_ENCODE_TABLE above, but with + and /
    092     * changed to - and _ to make the encoded Base64 results more URL-SAFE.
    093     * This table is only used when the Base64's mode is set to URL-SAFE.
    094     */
    095    private static final byte[] URL_SAFE_ENCODE_TABLE = {
    096            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
    097            'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
    098            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
    099            'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
    100            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_'
    101    };
    102
    103    /**
    104     * This array is a lookup table that translates Unicode characters drawn from the "Base64 Alphabet" (as specified
    105     * in Table 1 of RFC 2045) into their 6-bit positive integer equivalents. Characters that are not in the Base64
    106     * alphabet but fall within the bounds of the array are translated to -1.
    107     *
    108     * Note: '+' and '-' both decode to 62. '/' and '_' both decode to 63. This means decoder seamlessly handles both
    109     * URL_SAFE and STANDARD base64. (The encoder, on the other hand, needs to know ahead of time what to emit).
    110     *
    111     * Thanks to "commons" project in ws.apache.org for this code.
    112     * http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/
    113     */
    114    private static final byte[] DECODE_TABLE = {
    115        //   0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
    116            -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 00-0f
    117            -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 10-1f
    118            -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, 62, -1, 63, // 20-2f + - /
    119            52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, // 30-3f 0-9
    120            -1,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, // 40-4f A-O
    121            15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, 63, // 50-5f P-Z _
    122            -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, // 60-6f a-o
    123            41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51                      // 70-7a p-z
    124    };
    125
    126    /**
    127     * Base64 uses 6-bit fields.
    128     */
    129    /** Mask used to extract 6 bits, used when encoding */
    130    private static final int MASK_6BITS = 0x3f;
    131
    132    // The static final fields above are used for the original static byte[] methods on Base64.
    133    // The private member fields below are used with the new streaming approach, which requires
    134    // some state be preserved between calls of encode() and decode().
    135
    136    /**
    137     * Encode table to use: either STANDARD or URL_SAFE. Note: the DECODE_TABLE above remains static because it is able
    138     * to decode both STANDARD and URL_SAFE streams, but the encodeTable must be a member variable so we can switch
    139     * between the two modes.
    140     */
    141    private final byte[] encodeTable;
    142
    143    // Only one decode table currently; keep for consistency with Base32 code
    144    private final byte[] decodeTable = DECODE_TABLE;
    145
    146    /**
    147     * Line separator for encoding. Not used when decoding. Only used if lineLength &gt; 0.
    148     */
    149    private final byte[] lineSeparator;
    150
    151    /**
    152     * Convenience variable to help us determine when our buffer is going to run out of room and needs resizing.
    153     * <code>decodeSize = 3 + lineSeparator.length;</code>
    154     */
    155    private final int decodeSize;
    156
    157    /**
    158     * Convenience variable to help us determine when our buffer is going to run out of room and needs resizing.
    159     * <code>encodeSize = 4 + lineSeparator.length;</code>
    160     */
    161    private final int encodeSize;
    162
    163    /**
    164     * Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.
    165     * <p>
    166     * When encoding the line length is 0 (no chunking), and the encoding table is STANDARD_ENCODE_TABLE.
    167     * </p>
    168     *
    169     * <p>
    170     * When decoding all variants are supported.
    171     * </p>
    172     */
    173    public Base64() {
    174        this(0);
    175    }
    176
    177    /**
    178     * Creates a Base64 codec used for decoding (all modes) and encoding in the given URL-safe mode.
    179     * <p>
    180     * When encoding the line length is 76, the line separator is CRLF, and the encoding table is STANDARD_ENCODE_TABLE.
    181     * </p>
    182     *
    183     * <p>
    184     * When decoding all variants are supported.
    185     * </p>
    186     *
    187     * @param urlSafe
    188     *            if <code>true</code>, URL-safe encoding is used. In most cases this should be set to
    189     *            <code>false</code>.
    190     * @since 1.4
    191     */
    192    public Base64(final boolean urlSafe) {
    193        this(MIME_CHUNK_SIZE, CHUNK_SEPARATOR, urlSafe);
    194    }
    195
    196    /**
    197     * Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.
    198     * <p>
    199     * When encoding the line length is given in the constructor, the line separator is CRLF, and the encoding table is
    200     * STANDARD_ENCODE_TABLE.
    201     * </p>
    202     * <p>
    203     * Line lengths that aren't multiples of 4 will still essentially end up being multiples of 4 in the encoded data.
    204     * </p>
    205     * <p>
    206     * When decoding all variants are supported.
    207     * </p>
    208     *
    209     * @param lineLength
    210     *            Each line of encoded data will be at most of the given length (rounded down to nearest multiple of
    211     *            4). If lineLength &lt;= 0, then the output will not be divided into lines (chunks). Ignored when
    212     *            decoding.
    213     * @since 1.4
    214     */
    215    public Base64(final int lineLength) {
    216        this(lineLength, CHUNK_SEPARATOR);
    217    }
    218
    219    /**
    220     * Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.
    221     * <p>
    222     * When encoding the line length and line separator are given in the constructor, and the encoding table is
    223     * STANDARD_ENCODE_TABLE.
    224     * </p>
    225     * <p>
    226     * Line lengths that aren't multiples of 4 will still essentially end up being multiples of 4 in the encoded data.
    227     * </p>
    228     * <p>
    229     * When decoding all variants are supported.
    230     * </p>
    231     *
    232     * @param lineLength
    233     *            Each line of encoded data will be at most of the given length (rounded down to nearest multiple of
    234     *            4). If lineLength &lt;= 0, then the output will not be divided into lines (chunks). Ignored when
    235     *            decoding.
    236     * @param lineSeparator
    237     *            Each line of encoded data will end with this sequence of bytes.
    238     * @throws IllegalArgumentException
    239     *             Thrown when the provided lineSeparator included some base64 characters.
    240     * @since 1.4
    241     */
    242    public Base64(final int lineLength, final byte[] lineSeparator) {
    243        this(lineLength, lineSeparator, false);
    244    }
    245
    246    /**
    247     * Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.
    248     * <p>
    249     * When encoding the line length and line separator are given in the constructor, and the encoding table is
    250     * STANDARD_ENCODE_TABLE.
    251     * </p>
    252     * <p>
    253     * Line lengths that aren't multiples of 4 will still essentially end up being multiples of 4 in the encoded data.
    254     * </p>
    255     * <p>
    256     * When decoding all variants are supported.
    257     * </p>
    258     *
    259     * @param lineLength
    260     *            Each line of encoded data will be at most of the given length (rounded down to nearest multiple of
    261     *            4). If lineLength &lt;= 0, then the output will not be divided into lines (chunks). Ignored when
    262     *            decoding.
    263     * @param lineSeparator
    264     *            Each line of encoded data will end with this sequence of bytes.
    265     * @param urlSafe
    266     *            Instead of emitting '+' and '/' we emit '-' and '_' respectively. urlSafe is only applied to encode
    267     *            operations. Decoding seamlessly handles both modes.
    268     *            <b>Note: no padding is added when using the URL-safe alphabet.</b>
    269     * @throws IllegalArgumentException
    270     *             The provided lineSeparator included some base64 characters. That's not going to work!
    271     * @since 1.4
    272     */
    273    public Base64(final int lineLength, final byte[] lineSeparator, final boolean urlSafe) {
    274        super(BYTES_PER_UNENCODED_BLOCK, BYTES_PER_ENCODED_BLOCK,
    275                lineLength,
    276                lineSeparator == null ? 0 : lineSeparator.length);
    277        // TODO could be simplified if there is no requirement to reject invalid line sep when length <=0
    278        // @see test case Base64Test.testConstructors()
    279        if (lineSeparator != null) {
    280            if (containsAlphabetOrPad(lineSeparator)) {
    281                final String sep = StringUtils.newStringUtf8(lineSeparator);
    282                throw new IllegalArgumentException("lineSeparator must not contain base64 characters: [" + sep + "]");
    283            }
    284            if (lineLength > 0){ // null line-sep forces no chunking rather than throwing IAE
    285                this.encodeSize = BYTES_PER_ENCODED_BLOCK + lineSeparator.length;
    286                this.lineSeparator = new byte[lineSeparator.length];
    287                System.arraycopy(lineSeparator, 0, this.lineSeparator, 0, lineSeparator.length);
    288            } else {
    289                this.encodeSize = BYTES_PER_ENCODED_BLOCK;
    290                this.lineSeparator = null;
    291            }
    292        } else {
    293            this.encodeSize = BYTES_PER_ENCODED_BLOCK;
    294            this.lineSeparator = null;
    295        }
    296        this.decodeSize = this.encodeSize - 1;
    297        this.encodeTable = urlSafe ? URL_SAFE_ENCODE_TABLE : STANDARD_ENCODE_TABLE;
    298    }
    299
    300    /**
    301     * Returns our current encode mode. True if we're URL-SAFE, false otherwise.
    302     *
    303     * @return true if we're in URL-SAFE mode, false otherwise.
    304     * @since 1.4
    305     */
    306    public boolean isUrlSafe() {
    307        return this.encodeTable == URL_SAFE_ENCODE_TABLE;
    308    }
    309
    310    /**
    311     * <p>
    312     * Encodes all of the provided data, starting at inPos, for inAvail bytes. Must be called at least twice: once with
    313     * the data to encode, and once with inAvail set to "-1" to alert encoder that EOF has been reached, to flush last
    314     * remaining bytes (if not multiple of 3).
    315     * </p>
    316     * <p><b>Note: no padding is added when encoding using the URL-safe alphabet.</b></p>
    317     * <p>
    318     * Thanks to "commons" project in ws.apache.org for the bitwise operations, and general approach.
    319     * http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/
    320     * </p>
    321     *
    322     * @param in
    323     *            byte[] array of binary data to base64 encode.
    324     * @param inPos
    325     *            Position to start reading data from.
    326     * @param inAvail
    327     *            Amount of bytes available from input for encoding.
    328     * @param context
    329     *            the context to be used
    330     */
    331    @Override
    332    void encode(final byte[] in, int inPos, final int inAvail, final Context context) {
    333        if (context.eof) {
    334            return;
    335        }
    336        // inAvail < 0 is how we're informed of EOF in the underlying data we're
    337        // encoding.
    338        if (inAvail < 0) {
    339            context.eof = true;
    340            if (0 == context.modulus && lineLength == 0) {
    341                return; // no leftovers to process and not using chunking
    342            }
    343            final byte[] buffer = ensureBufferSize(encodeSize, context);
    344            final int savedPos = context.pos;
    345            switch (context.modulus) { // 0-2
    346                case 0 : // nothing to do here
    347                    break;
    348                case 1 : // 8 bits = 6 + 2
    349                    // top 6 bits:
    350                    buffer[context.pos++] = encodeTable[(context.ibitWorkArea >> 2) & MASK_6BITS];
    351                    // remaining 2:
    352                    buffer[context.pos++] = encodeTable[(context.ibitWorkArea << 4) & MASK_6BITS];
    353                    // URL-SAFE skips the padding to further reduce size.
    354                    if (encodeTable == STANDARD_ENCODE_TABLE) {
    355                        buffer[context.pos++] = pad;
    356                        buffer[context.pos++] = pad;
    357                    }
    358                    break;
    359
    360                case 2 : // 16 bits = 6 + 6 + 4
    361                    buffer[context.pos++] = encodeTable[(context.ibitWorkArea >> 10) & MASK_6BITS];
    362                    buffer[context.pos++] = encodeTable[(context.ibitWorkArea >> 4) & MASK_6BITS];
    363                    buffer[context.pos++] = encodeTable[(context.ibitWorkArea << 2) & MASK_6BITS];
    364                    // URL-SAFE skips the padding to further reduce size.
    365                    if (encodeTable == STANDARD_ENCODE_TABLE) {
    366                        buffer[context.pos++] = pad;
    367                    }
    368                    break;
    369                default:
    370                    throw new IllegalStateException("Impossible modulus "+context.modulus);
    371            }
    372            context.currentLinePos += context.pos - savedPos; // keep track of current line position
    373            // if currentPos == 0 we are at the start of a line, so don't add CRLF
    374            if (lineLength > 0 && context.currentLinePos > 0) {
    375                System.arraycopy(lineSeparator, 0, buffer, context.pos, lineSeparator.length);
    376                context.pos += lineSeparator.length;
    377            }
    378        } else {
    379            for (int i = 0; i < inAvail; i++) {
    380                final byte[] buffer = ensureBufferSize(encodeSize, context);
    381                context.modulus = (context.modulus+1) % BYTES_PER_UNENCODED_BLOCK;
    382                int b = in[inPos++];
    383                if (b < 0) {
    384                    b += 256;
    385                }
    386                context.ibitWorkArea = (context.ibitWorkArea << 8) + b; //  BITS_PER_BYTE
    387                if (0 == context.modulus) { // 3 bytes = 24 bits = 4 * 6 bits to extract
    388                    buffer[context.pos++] = encodeTable[(context.ibitWorkArea >> 18) & MASK_6BITS];
    389                    buffer[context.pos++] = encodeTable[(context.ibitWorkArea >> 12) & MASK_6BITS];
    390                    buffer[context.pos++] = encodeTable[(context.ibitWorkArea >> 6) & MASK_6BITS];
    391                    buffer[context.pos++] = encodeTable[context.ibitWorkArea & MASK_6BITS];
    392                    context.currentLinePos += BYTES_PER_ENCODED_BLOCK;
    393                    if (lineLength > 0 && lineLength <= context.currentLinePos) {
    394                        System.arraycopy(lineSeparator, 0, buffer, context.pos, lineSeparator.length);
    395                        context.pos += lineSeparator.length;
    396                        context.currentLinePos = 0;
    397                    }
    398                }
    399            }
    400        }
    401    }
    402
    403    /**
    404     * <p>
    405     * Decodes all of the provided data, starting at inPos, for inAvail bytes. Should be called at least twice: once
    406     * with the data to decode, and once with inAvail set to "-1" to alert decoder that EOF has been reached. The "-1"
    407     * call is not necessary when decoding, but it doesn't hurt, either.
    408     * </p>
    409     * <p>
    410     * Ignores all non-base64 characters. This is how chunked (e.g. 76 character) data is handled, since CR and LF are
    411     * silently ignored, but has implications for other bytes, too. This method subscribes to the garbage-in,
    412     * garbage-out philosophy: it will not check the provided data for validity.
    413     * </p>
    414     * <p>
    415     * Thanks to "commons" project in ws.apache.org for the bitwise operations, and general approach.
    416     * http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/
    417     * </p>
    418     *
    419     * @param in
    420     *            byte[] array of ascii data to base64 decode.
    421     * @param inPos
    422     *            Position to start reading data from.
    423     * @param inAvail
    424     *            Amount of bytes available from input for decoding.
    425     * @param context
    426     *            the context to be used
    427     */
    428    @Override
    429    void decode(final byte[] in, int inPos, final int inAvail, final Context context) {
    430        if (context.eof) {
    431            return;
    432        }
    433        if (inAvail < 0) {
    434            context.eof = true;
    435        }
    436        for (int i = 0; i < inAvail; i++) {
    437            final byte[] buffer = ensureBufferSize(decodeSize, context);
    438            final byte b = in[inPos++];
    439            if (b == pad) {
    440                // We're done.
    441                context.eof = true;
    442                break;
    443            }
    444            if (b >= 0 && b < DECODE_TABLE.length) {
    445                final int result = DECODE_TABLE[b];
    446                if (result >= 0) {
    447                    context.modulus = (context.modulus+1) % BYTES_PER_ENCODED_BLOCK;
    448                    context.ibitWorkArea = (context.ibitWorkArea << BITS_PER_ENCODED_BYTE) + result;
    449                    if (context.modulus == 0) {
    450                        buffer[context.pos++] = (byte) ((context.ibitWorkArea >> 16) & MASK_8BITS);
    451                        buffer[context.pos++] = (byte) ((context.ibitWorkArea >> 8) & MASK_8BITS);
    452                        buffer[context.pos++] = (byte) (context.ibitWorkArea & MASK_8BITS);
    453                    }
    454                }
    455            }
    456        }
    457
    458        // Two forms of EOF as far as base64 decoder is concerned: actual
    459        // EOF (-1) and first time '=' character is encountered in stream.
    460        // This approach makes the '=' padding characters completely optional.
    461        if (context.eof && context.modulus != 0) {
    462            final byte[] buffer = ensureBufferSize(decodeSize, context);
    463
    464            // We have some spare bits remaining
    465            // Output all whole multiples of 8 bits and ignore the rest
    466            switch (context.modulus) {
    467//              case 0 : // impossible, as excluded above
    468                case 1 : // 6 bits - ignore entirely
    469                    // TODO not currently tested; perhaps it is impossible?
    470                    break;
    471                case 2 : // 12 bits = 8 + 4
    472                    validateCharacter(4, context);
    473                    context.ibitWorkArea = context.ibitWorkArea >> 4; // dump the extra 4 bits
    474                    buffer[context.pos++] = (byte) ((context.ibitWorkArea) & MASK_8BITS);
    475                    break;
    476                case 3 : // 18 bits = 8 + 8 + 2
    477                    validateCharacter(2, context);
    478                    context.ibitWorkArea = context.ibitWorkArea >> 2; // dump 2 bits
    479                    buffer[context.pos++] = (byte) ((context.ibitWorkArea >> 8) & MASK_8BITS);
    480                    buffer[context.pos++] = (byte) ((context.ibitWorkArea) & MASK_8BITS);
    481                    break;
    482                default:
    483                    throw new IllegalStateException("Impossible modulus "+context.modulus);
    484            }
    485        }
    486    }
    487
    488    /**
    489     * Tests a given byte array to see if it contains only valid characters within the Base64 alphabet. Currently the
    490     * method treats whitespace as valid.
    491     *
    492     * @param arrayOctet
    493     *            byte array to test
    494     * @return <code>true</code> if all bytes are valid characters in the Base64 alphabet or if the byte array is empty;
    495     *         <code>false</code>, otherwise
    496     * @deprecated 1.5 Use {@link #isBase64(byte[])}, will be removed in 2.0.
    497     */
    498    @Deprecated
    499    public static boolean isArrayByteBase64(final byte[] arrayOctet) {
    500        return isBase64(arrayOctet);
    501    }
    502
    503    /**
    504     * Returns whether or not the <code>octet</code> is in the base 64 alphabet.
    505     *
    506     * @param octet
    507     *            The value to test
    508     * @return <code>true</code> if the value is defined in the the base 64 alphabet, <code>false</code> otherwise.
    509     * @since 1.4
    510     */
    511    public static boolean isBase64(final byte octet) {
    512        return octet == PAD_DEFAULT || (octet >= 0 && octet < DECODE_TABLE.length && DECODE_TABLE[octet] != -1);
    513    }
    514
    515    /**
    516     * Tests a given String to see if it contains only valid characters within the Base64 alphabet. Currently the
    517     * method treats whitespace as valid.
    518     *
    519     * @param base64
    520     *            String to test
    521     * @return <code>true</code> if all characters in the String are valid characters in the Base64 alphabet or if
    522     *         the String is empty; <code>false</code>, otherwise
    523     *  @since 1.5
    524     */
    525    public static boolean isBase64(final String base64) {
    526        return isBase64(StringUtils.getBytesUtf8(base64));
    527    }
    528
    529    /**
    530     * Tests a given byte array to see if it contains only valid characters within the Base64 alphabet. Currently the
    531     * method treats whitespace as valid.
    532     *
    533     * @param arrayOctet
    534     *            byte array to test
    535     * @return <code>true</code> if all bytes are valid characters in the Base64 alphabet or if the byte array is empty;
    536     *         <code>false</code>, otherwise
    537     * @since 1.5
    538     */
    539    public static boolean isBase64(final byte[] arrayOctet) {
    540        for (int i = 0; i < arrayOctet.length; i++) {
    541            if (!isBase64(arrayOctet[i]) && !isWhiteSpace(arrayOctet[i])) {
    542                return false;
    543            }
    544        }
    545        return true;
    546    }
    547
    548    /**
    549     * Encodes binary data using the base64 algorithm but does not chunk the output.
    550     *
    551     * @param binaryData
    552     *            binary data to encode
    553     * @return byte[] containing Base64 characters in their UTF-8 representation.
    554     */
    555    public static byte[] encodeBase64(final byte[] binaryData) {
    556        return encodeBase64(binaryData, false);
    557    }
    558
    559    /**
    560     * Encodes binary data using the base64 algorithm but does not chunk the output.
    561     *
    562     * NOTE:  We changed the behaviour of this method from multi-line chunking (commons-codec-1.4) to
    563     * single-line non-chunking (commons-codec-1.5).
    564     *
    565     * @param binaryData
    566     *            binary data to encode
    567     * @return String containing Base64 characters.
    568     * @since 1.4 (NOTE:  1.4 chunked the output, whereas 1.5 does not).
    569     */
    570    public static String encodeBase64String(final byte[] binaryData) {
    571        return StringUtils.newStringUsAscii(encodeBase64(binaryData, false));
    572    }
    573
    574    /**
    575     * Encodes binary data using a URL-safe variation of the base64 algorithm but does not chunk the output. The
    576     * url-safe variation emits - and _ instead of + and / characters.
    577     * <b>Note: no padding is added.</b>
    578     * @param binaryData
    579     *            binary data to encode
    580     * @return byte[] containing Base64 characters in their UTF-8 representation.
    581     * @since 1.4
    582     */
    583    public static byte[] encodeBase64URLSafe(final byte[] binaryData) {
    584        return encodeBase64(binaryData, false, true);
    585    }
    586
    587    /**
    588     * Encodes binary data using a URL-safe variation of the base64 algorithm but does not chunk the output. The
    589     * url-safe variation emits - and _ instead of + and / characters.
    590     * <b>Note: no padding is added.</b>
    591     * @param binaryData
    592     *            binary data to encode
    593     * @return String containing Base64 characters
    594     * @since 1.4
    595     */
    596    public static String encodeBase64URLSafeString(final byte[] binaryData) {
    597        return StringUtils.newStringUsAscii(encodeBase64(binaryData, false, true));
    598    }
    599
    600    /**
    601     * Encodes binary data using the base64 algorithm and chunks the encoded output into 76 character blocks
    602     *
    603     * @param binaryData
    604     *            binary data to encode
    605     * @return Base64 characters chunked in 76 character blocks
    606     */
    607    public static byte[] encodeBase64Chunked(final byte[] binaryData) {
    608        return encodeBase64(binaryData, true);
    609    }
    610
    611    /**
    612     * Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks.
    613     *
    614     * @param binaryData
    615     *            Array containing binary data to encode.
    616     * @param isChunked
    617     *            if <code>true</code> this encoder will chunk the base64 output into 76 character blocks
    618     * @return Base64-encoded data.
    619     * @throws IllegalArgumentException
    620     *             Thrown when the input array needs an output array bigger than {@link Integer#MAX_VALUE}
    621     */
    622    public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked) {
    623        return encodeBase64(binaryData, isChunked, false);
    624    }
    625
    626    /**
    627     * Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks.
    628     *
    629     * @param binaryData
    630     *            Array containing binary data to encode.
    631     * @param isChunked
    632     *            if <code>true</code> this encoder will chunk the base64 output into 76 character blocks
    633     * @param urlSafe
    634     *            if <code>true</code> this encoder will emit - and _ instead of the usual + and / characters.
    635     *            <b>Note: no padding is added when encoding using the URL-safe alphabet.</b>
    636     * @return Base64-encoded data.
    637     * @throws IllegalArgumentException
    638     *             Thrown when the input array needs an output array bigger than {@link Integer#MAX_VALUE}
    639     * @since 1.4
    640     */
    641    public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe) {
    642        return encodeBase64(binaryData, isChunked, urlSafe, Integer.MAX_VALUE);
    643    }
    644
    645    /**
    646     * Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks.
    647     *
    648     * @param binaryData
    649     *            Array containing binary data to encode.
    650     * @param isChunked
    651     *            if <code>true</code> this encoder will chunk the base64 output into 76 character blocks
    652     * @param urlSafe
    653     *            if <code>true</code> this encoder will emit - and _ instead of the usual + and / characters.
    654     *            <b>Note: no padding is added when encoding using the URL-safe alphabet.</b>
    655     * @param maxResultSize
    656     *            The maximum result size to accept.
    657     * @return Base64-encoded data.
    658     * @throws IllegalArgumentException
    659     *             Thrown when the input array needs an output array bigger than maxResultSize
    660     * @since 1.4
    661     */
    662    public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked,
    663                                      final boolean urlSafe, final int maxResultSize) {
    664        if (binaryData == null || binaryData.length == 0) {
    665            return binaryData;
    666        }
    667
    668        // Create this so can use the super-class method
    669        // Also ensures that the same roundings are performed by the ctor and the code
    670        final Base64 b64 = isChunked ? new Base64(urlSafe) : new Base64(0, CHUNK_SEPARATOR, urlSafe);
    671        final long len = b64.getEncodedLength(binaryData);
    672        if (len > maxResultSize) {
    673            throw new IllegalArgumentException("Input array too big, the output array would be bigger (" +
    674                len +
    675                ") than the specified maximum size of " +
    676                maxResultSize);
    677        }
    678
    679        return b64.encode(binaryData);
    680    }
    681
    682    /**
    683     * Decodes a Base64 String into octets.
    684     * <p>
    685     * <b>Note:</b> this method seamlessly handles data encoded in URL-safe or normal mode.
    686     * </p>
    687     *
    688     * @param base64String
    689     *            String containing Base64 data
    690     * @return Array containing decoded data.
    691     * @since 1.4
    692     */
    693    public static byte[] decodeBase64(final String base64String) {
    694        return new Base64().decode(base64String);
    695    }
    696
    697    /**
    698     * Decodes Base64 data into octets.
    699     * <p>
    700     * <b>Note:</b> this method seamlessly handles data encoded in URL-safe or normal mode.
    701     * </p>
    702     *
    703     * @param base64Data
    704     *            Byte array containing Base64 data
    705     * @return Array containing decoded data.
    706     */
    707    public static byte[] decodeBase64(final byte[] base64Data) {
    708        return new Base64().decode(base64Data);
    709    }
    710
    711    // Implementation of the Encoder Interface
    712
    713    // Implementation of integer encoding used for crypto
    714    /**
    715     * Decodes a byte64-encoded integer according to crypto standards such as W3C's XML-Signature.
    716     *
    717     * @param pArray
    718     *            a byte array containing base64 character data
    719     * @return A BigInteger
    720     * @since 1.4
    721     */
    722    public static BigInteger decodeInteger(final byte[] pArray) {
    723        return new BigInteger(1, decodeBase64(pArray));
    724    }
    725
    726    /**
    727     * Encodes to a byte64-encoded integer according to crypto standards such as W3C's XML-Signature.
    728     *
    729     * @param bigInt
    730     *            a BigInteger
    731     * @return A byte array containing base64 character data
    732     * @throws NullPointerException
    733     *             if null is passed in
    734     * @since 1.4
    735     */
    736    public static byte[] encodeInteger(final BigInteger bigInt) {
    737        if (bigInt == null) {
    738            throw new NullPointerException("encodeInteger called with null parameter");
    739        }
    740        return encodeBase64(toIntegerBytes(bigInt), false);
    741    }
    742
    743    /**
    744     * Returns a byte-array representation of a <code>BigInteger</code> without sign bit.
    745     *
    746     * @param bigInt
    747     *            <code>BigInteger</code> to be converted
    748     * @return a byte array representation of the BigInteger parameter
    749     */
    750    static byte[] toIntegerBytes(final BigInteger bigInt) {
    751        int bitlen = bigInt.bitLength();
    752        // round bitlen
    753        bitlen = ((bitlen + 7) >> 3) << 3;
    754        final byte[] bigBytes = bigInt.toByteArray();
    755
    756        if (((bigInt.bitLength() % 8) != 0) && (((bigInt.bitLength() / 8) + 1) == (bitlen / 8))) {
    757            return bigBytes;
    758        }
    759        // set up params for copying everything but sign bit
    760        int startSrc = 0;
    761        int len = bigBytes.length;
    762
    763        // if bigInt is exactly byte-aligned, just skip signbit in copy
    764        if ((bigInt.bitLength() % 8) == 0) {
    765            startSrc = 1;
    766            len--;
    767        }
    768        final int startDst = bitlen / 8 - len; // to pad w/ nulls as per spec
    769        final byte[] resizedBytes = new byte[bitlen / 8];
    770        System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, len);
    771        return resizedBytes;
    772    }
    773
    774    /**
    775     * Returns whether or not the <code>octet</code> is in the Base64 alphabet.
    776     *
    777     * @param octet
    778     *            The value to test
    779     * @return <code>true</code> if the value is defined in the the Base64 alphabet <code>false</code> otherwise.
    780     */
    781    @Override
    782    protected boolean isInAlphabet(final byte octet) {
    783        return octet >= 0 && octet < decodeTable.length && decodeTable[octet] != -1;
    784    }
    785
    786    /**
    787     * <p>
    788     * Validates whether the character is possible in the context of the set of possible base 64 values.
    789     * </p>
    790     *
    791     * @param numBits number of least significant bits to check
    792     * @param context the context to be used
    793     *
    794     * @throws IllegalArgumentException if the bits being checked contain any non-zero value
    795     */
    796    private long validateCharacter(final int numBitsToDrop, final Context context) {
    797        if ((context.ibitWorkArea & numBitsToDrop) != 0) {
    798        throw new IllegalArgumentException(
    799            "Last encoded character (before the paddings if any) is a valid base 64 alphabet but not a possible value");
    800        }
    801        return context.ibitWorkArea >> numBitsToDrop;
    802    }
    803}