    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.net.util;
    019
    020import java.io.UnsupportedEncodingException;
    021import java.math.BigInteger;
    022
    023
    024
    025/**
    026 * Provides Base64 encoding and decoding as defined by RFC 2045.
    027 *
    028 * <p>
    029 * This class implements section <cite>6.8. Base64 Content-Transfer-Encoding</cite> from RFC 2045 <cite>Multipurpose
    030 * Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies</cite> by Freed and Borenstein.
    031 * </p>
    032 * <p>
    033 * The class can be parameterized in the following manner with various constructors:
    034 * <ul>
    035 * <li>URL-safe mode: Default off.</li>
    036 * <li>Line length: Default 76. Line length that aren't multiples of 4 will still essentially end up being multiples of
    037 * 4 in the encoded data.
    038 * <li>Line separator: Default is CRLF ("\r\n")</li>
    039 * </ul>
    040 * </p>
    041 * <p>
    042 * Since this class operates directly on byte streams, and not character streams, it is hard-coded to only encode/decode
    043 * character encodings which are compatible with the lower 127 ASCII chart (ISO-8859-1, Windows-1252, UTF-8, etc).
    044 * </p>
    045 *
    046 * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>
    047 * @author Apache Software Foundation
    048 * @since 2.2
    049 * @version $Id: Base64.java 1489533 2013-06-04 17:49:00Z sebb $
    050 */
    051public class Base64 {
    052    private static final int DEFAULT_BUFFER_RESIZE_FACTOR = 2;
    053
    054    private static final int DEFAULT_BUFFER_SIZE = 8192;
    055
    056    /**
    057     * Chunk size per RFC 2045 section 6.8.
    058     *
    059     * <p>
    060     * The {@value} character limit does not count the trailing CRLF, but counts all other characters, including any
    061     * equal signs.
    062     * </p>
    063     *
    064     * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 6.8</a>
    065     */
    066    static final int CHUNK_SIZE = 76;
    067
    068    /**
    069     * Chunk separator per RFC 2045 section 2.1.
    070     *
    071     * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 2.1</a>
    072     */
    073    private static final byte[] CHUNK_SEPARATOR = {'\r', '\n'};
    074
    075    private static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
    076
    077    /**
    078     * This array is a lookup table that translates 6-bit positive integer index values into their "Base64 Alphabet"
    079     * equivalents as specified in Table 1 of RFC 2045.
    080     *
    081     * Thanks to "commons" project in ws.apache.org for this code.
    082     * http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/
    083     */
    084    private static final byte[] STANDARD_ENCODE_TABLE = {
    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            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
    088            'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
    089            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
    090    };
    091
    092    /**
    093     * This is a copy of the STANDARD_ENCODE_TABLE above, but with + and /
    094     * changed to - and _ to make the encoded Base64 results more URL-SAFE.
    095     * This table is only used when the Base64's mode is set to URL-SAFE.
    096     */
    097    private static final byte[] URL_SAFE_ENCODE_TABLE = {
    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            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
    101            'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
    102            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_'
    103    };
    104
    105    /**
    106     * Byte used to pad output.
    107     */
    108    private static final byte PAD = '=';
    109
    110    /**
    111     * This array is a lookup table that translates Unicode characters drawn from the "Base64 Alphabet" (as specified in
    112     * Table 1 of RFC 2045) into their 6-bit positive integer equivalents. Characters that are not in the Base64
    113     * alphabet but fall within the bounds of the array are translated to -1.
    114     *
    115     * Note: '+' and '-' both decode to 62. '/' and '_' both decode to 63. This means decoder seamlessly handles both
    116     * URL_SAFE and STANDARD base64. (The encoder, on the other hand, needs to know ahead of time what to emit).
    117     *
    118     * Thanks to "commons" project in ws.apache.org for this code.
    119     * http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/
    120     */
    121    private static final byte[] DECODE_TABLE = {
    122            -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    123            -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    124            -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, 62, -1, 63, 52, 53, 54,
    125            55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4,
    126            5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
    127            24, 25, -1, -1, -1, -1, 63, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34,
    128            35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51
    129    };
    130
    131    /** Mask used to extract 6 bits, used when encoding */
    132    private static final int MASK_6BITS = 0x3f;
    133
    134    /** Mask used to extract 8 bits, used in decoding base64 bytes */
    135    private static final int MASK_8BITS = 0xff;
    136
    137    // The static final fields above are used for the original static byte[] methods on Base64.
    138    // The private member fields below are used with the new streaming approach, which requires
    139    // some state be preserved between calls of encode() and decode().
    140
    141    /**
    142     * Encode table to use: either STANDARD or URL_SAFE. Note: the DECODE_TABLE above remains static because it is able
    143     * to decode both STANDARD and URL_SAFE streams, but the encodeTable must be a member variable so we can switch
    144     * between the two modes.
    145     */
    146    private final byte[] encodeTable;
    147
    148    /**
    149     * Line length for encoding. Not used when decoding. A value of zero or less implies no chunking of the base64
    150     * encoded data.
    151     */
    152    private final int lineLength;
    153
    154    /**
    155     * Line separator for encoding. Not used when decoding. Only used if lineLength > 0.
    156     */
    157    private final byte[] lineSeparator;
    158
    159    /**
    160     * Convenience variable to help us determine when our buffer is going to run out of room and needs resizing.
    161     * <code>decodeSize = 3 + lineSeparator.length;</code>
    162     */
    163    private final int decodeSize;
    164
    165    /**
    166     * Convenience variable to help us determine when our buffer is going to run out of room and needs resizing.
    167     * <code>encodeSize = 4 + lineSeparator.length;</code>
    168     */
    169    private final int encodeSize;
    170
    171    /**
    172     * Buffer for streaming.
    173     */
    174    private byte[] buffer;
    175
    176    /**
    177     * Position where next character should be written in the buffer.
    178     */
    179    private int pos;
    180
    181    /**
    182     * Position where next character should be read from the buffer.
    183     */
    184    private int readPos;
    185
    186    /**
    187     * Variable tracks how many characters have been written to the current line. Only used when encoding. We use it to
    188     * make sure each encoded line never goes beyond lineLength (if lineLength > 0).
    189     */
    190    private int currentLinePos;
    191
    192    /**
    193     * Writes to the buffer only occur after every 3 reads when encoding, an every 4 reads when decoding. This variable
    194     * helps track that.
    195     */
    196    private int modulus;
    197
    198    /**
    199     * Boolean flag to indicate the EOF has been reached. Once EOF has been reached, this Base64 object becomes useless,
    200     * and must be thrown away.
    201     */
    202    private boolean eof;
    203
    204    /**
    205     * Place holder for the 3 bytes we're dealing with for our base64 logic. Bitwise operations store and extract the
    206     * base64 encoding or decoding from this variable.
    207     */
    208    private int x;
    209
    210    /**
    211     * Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.
    212     * <p>
    213     * When encoding the line length is 76, the line separator is CRLF, and the encoding table is STANDARD_ENCODE_TABLE.
    214     * </p>
    215     *
    216     * <p>
    217     * When decoding all variants are supported.
    218     * </p>
    219     */
    220    public Base64() {
    221        this(false);
    222    }
    223
    224    /**
    225     * Creates a Base64 codec used for decoding (all modes) and encoding in the given URL-safe mode.
    226     * <p>
    227     * When encoding the line length is 76, the line separator is CRLF, and the encoding table is STANDARD_ENCODE_TABLE.
    228     * </p>
    229     *
    230     * <p>
    231     * When decoding all variants are supported.
    232     * </p>
    233     *
    234     * @param urlSafe
    235     *            if <code>true</code>, URL-safe encoding is used. In most cases this should be set to
    236     *            <code>false</code>.
    237     * @since 1.4
    238     */
    239    public Base64(boolean urlSafe) {
    240        this(CHUNK_SIZE, CHUNK_SEPARATOR, urlSafe);
    241    }
    242
    243    /**
    244     * Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.
    245     * <p>
    246     * When encoding the line length is given in the constructor, the line separator is CRLF, and the encoding table is
    247     * STANDARD_ENCODE_TABLE.
    248     * </p>
    249     * <p>
    250     * Line lengths that aren't multiples of 4 will still essentially end up being multiples of 4 in the encoded data.
    251     * </p>
    252     * <p>
    253     * When decoding all variants are supported.
    254     * </p>
    255     *
    256     * @param lineLength
    257     *            Each line of encoded data will be at most of the given length (rounded down to nearest multiple of 4).
    258     *            If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when decoding.
    259     * @since 1.4
    260     */
    261    public Base64(int lineLength) {
    262        this(lineLength, CHUNK_SEPARATOR);
    263    }
    264
    265    /**
    266     * Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.
    267     * <p>
    268     * When encoding the line length and line separator are given in the constructor, and the encoding table is
    269     * STANDARD_ENCODE_TABLE.
    270     * </p>
    271     * <p>
    272     * Line lengths that aren't multiples of 4 will still essentially end up being multiples of 4 in the encoded data.
    273     * </p>
    274     * <p>
    275     * When decoding all variants are supported.
    276     * </p>
    277     *
    278     * @param lineLength
    279     *            Each line of encoded data will be at most of the given length (rounded down to nearest multiple of 4).
    280     *            If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when decoding.
    281     * @param lineSeparator
    282     *            Each line of encoded data will end with this sequence of bytes.
    283     * @throws IllegalArgumentException
    284     *             Thrown when the provided lineSeparator included some base64 characters.
    285     * @since 1.4
    286     */
    287    public Base64(int lineLength, byte[] lineSeparator) {
    288        this(lineLength, lineSeparator, false);
    289    }
    290
    291    /**
    292     * Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.
    293     * <p>
    294     * When encoding the line length and line separator are given in the constructor, and the encoding table is
    295     * STANDARD_ENCODE_TABLE.
    296     * </p>
    297     * <p>
    298     * Line lengths that aren't multiples of 4 will still essentially end up being multiples of 4 in the encoded data.
    299     * </p>
    300     * <p>
    301     * When decoding all variants are supported.
    302     * </p>
    303     *
    304     * @param lineLength
    305     *            Each line of encoded data will be at most of the given length (rounded down to nearest multiple of 4).
    306     *            If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when decoding.
    307     * @param lineSeparator
    308     *            Each line of encoded data will end with this sequence of bytes.
    309     * @param urlSafe
    310     *            Instead of emitting '+' and '/' we emit '-' and '_' respectively. urlSafe is only applied to encode
    311     *            operations. Decoding seamlessly handles both modes.
    312     * @throws IllegalArgumentException
    313     *             The provided lineSeparator included some base64 characters. That's not going to work!
    314     * @since 1.4
    315     */
    316    public Base64(int lineLength, byte[] lineSeparator, boolean urlSafe) {
    317        if (lineSeparator == null) {
    318            lineLength = 0;  // disable chunk-separating
    319            lineSeparator = EMPTY_BYTE_ARRAY;  // this just gets ignored
    320        }
    321        this.lineLength = lineLength > 0 ? (lineLength / 4) * 4 : 0;
    322        this.lineSeparator = new byte[lineSeparator.length];
    323        System.arraycopy(lineSeparator, 0, this.lineSeparator, 0, lineSeparator.length);
    324        if (lineLength > 0) {
    325            this.encodeSize = 4 + lineSeparator.length;
    326        } else {
    327            this.encodeSize = 4;
    328        }
    329        this.decodeSize = this.encodeSize - 1;
    330        if (containsBase64Byte(lineSeparator)) {
    331            String sep = newStringUtf8(lineSeparator);
    332            throw new IllegalArgumentException("lineSeperator must not contain base64 characters: [" + sep + "]");
    333        }
    334        this.encodeTable = urlSafe ? URL_SAFE_ENCODE_TABLE : STANDARD_ENCODE_TABLE;
    335    }
    336
    337    /**
    338     * Returns our current encode mode. True if we're URL-SAFE, false otherwise.
    339     *
    340     * @return true if we're in URL-SAFE mode, false otherwise.
    341     * @since 1.4
    342     */
    343    public boolean isUrlSafe() {
    344        return this.encodeTable == URL_SAFE_ENCODE_TABLE;
    345    }
    346
    347    /**
    348     * Returns true if this Base64 object has buffered data for reading.
    349     *
    350     * @return true if there is Base64 object still available for reading.
    351     */
    352    boolean hasData() {
    353        return this.buffer != null;
    354    }
    355
    356    /**
    357     * Returns the amount of buffered data available for reading.
    358     *
    359     * @return The amount of buffered data available for reading.
    360     */
    361    int avail() {
    362        return buffer != null ? pos - readPos : 0;
    363    }
    364
    365    /** Doubles our buffer. */
    366    private void resizeBuffer() {
    367        if (buffer == null) {
    368            buffer = new byte[DEFAULT_BUFFER_SIZE];
    369            pos = 0;
    370            readPos = 0;
    371        } else {
    372            byte[] b = new byte[buffer.length * DEFAULT_BUFFER_RESIZE_FACTOR];
    373            System.arraycopy(buffer, 0, b, 0, buffer.length);
    374            buffer = b;
    375        }
    376    }
    377
    378    /**
    379     * Extracts buffered data into the provided byte[] array, starting at position bPos, up to a maximum of bAvail
    380     * bytes. Returns how many bytes were actually extracted.
    381     *
    382     * @param b
    383     *            byte[] array to extract the buffered data into.
    384     * @param bPos
    385     *            position in byte[] array to start extraction at.
    386     * @param bAvail
    387     *            amount of bytes we're allowed to extract. We may extract fewer (if fewer are available).
    388     * @return The number of bytes successfully extracted into the provided byte[] array.
    389     */
    390    int readResults(byte[] b, int bPos, int bAvail) {
    391        if (buffer != null) {
    392            int len = Math.min(avail(), bAvail);
    393            if (buffer != b) {
    394                System.arraycopy(buffer, readPos, b, bPos, len);
    395                readPos += len;
    396                if (readPos >= pos) {
    397                    buffer = null;
    398                }
    399            } else {
    400                // Re-using the original consumer's output array is only
    401                // allowed for one round.
    402                buffer = null;
    403            }
    404            return len;
    405        }
    406        return eof ? -1 : 0;
    407    }
    408
    409    /**
    410     * Sets the streaming buffer. This is a small optimization where we try to buffer directly to the consumer's output
    411     * array for one round (if the consumer calls this method first) instead of starting our own buffer.
    412     *
    413     * @param out
    414     *            byte[] array to buffer directly to.
    415     * @param outPos
    416     *            Position to start buffering into.
    417     * @param outAvail
    418     *            Amount of bytes available for direct buffering.
    419     */
    420    void setInitialBuffer(byte[] out, int outPos, int outAvail) {
    421        // We can re-use consumer's original output array under
    422        // special circumstances, saving on some System.arraycopy().
    423        if (out != null && out.length == outAvail) {
    424            buffer = out;
    425            pos = outPos;
    426            readPos = outPos;
    427        }
    428    }
    429
    430    /**
    431     * <p>
    432     * Encodes all of the provided data, starting at inPos, for inAvail bytes. Must be called at least twice: once with
    433     * the data to encode, and once with inAvail set to "-1" to alert encoder that EOF has been reached, so flush last
    434     * remaining bytes (if not multiple of 3).
    435     * </p>
    436     * <p>
    437     * Thanks to "commons" project in ws.apache.org for the bitwise operations, and general approach.
    438     * http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/
    439     * </p>
    440     *
    441     * @param in
    442     *            byte[] array of binary data to base64 encode.
    443     * @param inPos
    444     *            Position to start reading data from.
    445     * @param inAvail
    446     *            Amount of bytes available from input for encoding.
    447     */
    448    void encode(byte[] in, int inPos, int inAvail) {
    449        if (eof) {
    450            return;
    451        }
    452        // inAvail < 0 is how we're informed of EOF in the underlying data we're
    453        // encoding.
    454        if (inAvail < 0) {
    455            eof = true;
    456            if (buffer == null || buffer.length - pos < encodeSize) {
    457                resizeBuffer();
    458            }
    459            switch (modulus) {
    460                case 1 :
    461                    buffer[pos++] = encodeTable[(x >> 2) & MASK_6BITS];
    462                    buffer[pos++] = encodeTable[(x << 4) & MASK_6BITS];
    463                    // URL-SAFE skips the padding to further reduce size.
    464                    if (encodeTable == STANDARD_ENCODE_TABLE) {
    465                        buffer[pos++] = PAD;
    466                        buffer[pos++] = PAD;
    467                    }
    468                    break;
    469
    470                case 2 :
    471                    buffer[pos++] = encodeTable[(x >> 10) & MASK_6BITS];
    472                    buffer[pos++] = encodeTable[(x >> 4) & MASK_6BITS];
    473                    buffer[pos++] = encodeTable[(x << 2) & MASK_6BITS];
    474                    // URL-SAFE skips the padding to further reduce size.
    475                    if (encodeTable == STANDARD_ENCODE_TABLE) {
    476                        buffer[pos++] = PAD;
    477                    }
    478                    break;
    479                default:
    480                    break;  // other values ignored
    481            }
    482            if (lineLength > 0 && pos > 0) {
    483                System.arraycopy(lineSeparator, 0, buffer, pos, lineSeparator.length);
    484                pos += lineSeparator.length;
    485            }
    486        } else {
    487            for (int i = 0; i < inAvail; i++) {
    488                if (buffer == null || buffer.length - pos < encodeSize) {
    489                    resizeBuffer();
    490                }
    491                modulus = (++modulus) % 3;
    492                int b = in[inPos++];
    493                if (b < 0) {
    494                    b += 256;
    495                }
    496                x = (x << 8) + b;
    497                if (0 == modulus) {
    498                    buffer[pos++] = encodeTable[(x >> 18) & MASK_6BITS];
    499                    buffer[pos++] = encodeTable[(x >> 12) & MASK_6BITS];
    500                    buffer[pos++] = encodeTable[(x >> 6) & MASK_6BITS];
    501                    buffer[pos++] = encodeTable[x & MASK_6BITS];
    502                    currentLinePos += 4;
    503                    if (lineLength > 0 && lineLength <= currentLinePos) {
    504                        System.arraycopy(lineSeparator, 0, buffer, pos, lineSeparator.length);
    505                        pos += lineSeparator.length;
    506                        currentLinePos = 0;
    507                    }
    508                }
    509            }
    510        }
    511    }
    512
    513    /**
    514     * <p>
    515     * Decodes all of the provided data, starting at inPos, for inAvail bytes. Should be called at least twice: once
    516     * with the data to decode, and once with inAvail set to "-1" to alert decoder that EOF has been reached. The "-1"
    517     * call is not necessary when decoding, but it doesn't hurt, either.
    518     * </p>
    519     * <p>
    520     * Ignores all non-base64 characters. This is how chunked (e.g. 76 character) data is handled, since CR and LF are
    521     * silently ignored, but has implications for other bytes, too. This method subscribes to the garbage-in,
    522     * garbage-out philosophy: it will not check the provided data for validity.
    523     * </p>
    524     * <p>
    525     * Thanks to "commons" project in ws.apache.org for the bitwise operations, and general approach.
    526     * http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/
    527     * </p>
    528     *
    529     * @param in
    530     *            byte[] array of ascii data to base64 decode.
    531     * @param inPos
    532     *            Position to start reading data from.
    533     * @param inAvail
    534     *            Amount of bytes available from input for encoding.
    535     */
    536    void decode(byte[] in, int inPos, int inAvail) {
    537        if (eof) {
    538            return;
    539        }
    540        if (inAvail < 0) {
    541            eof = true;
    542        }
    543        for (int i = 0; i < inAvail; i++) {
    544            if (buffer == null || buffer.length - pos < decodeSize) {
    545                resizeBuffer();
    546            }
    547            byte b = in[inPos++];
    548            if (b == PAD) {
    549                // We're done.
    550                eof = true;
    551                break;
    552            } else {
    553                if (b >= 0 && b < DECODE_TABLE.length) {
    554                    int result = DECODE_TABLE[b];
    555                    if (result >= 0) {
    556                        modulus = (++modulus) % 4;
    557                        x = (x << 6) + result;
    558                        if (modulus == 0) {
    559                            buffer[pos++] = (byte) ((x >> 16) & MASK_8BITS);
    560                            buffer[pos++] = (byte) ((x >> 8) & MASK_8BITS);
    561                            buffer[pos++] = (byte) (x & MASK_8BITS);
    562                        }
    563                    }
    564                }
    565            }
    566        }
    567
    568        // Two forms of EOF as far as base64 decoder is concerned: actual
    569        // EOF (-1) and first time '=' character is encountered in stream.
    570        // This approach makes the '=' padding characters completely optional.
    571        if (eof && modulus != 0) {
    572            x = x << 6;
    573            switch (modulus) {
    574                case 2 :
    575                    x = x << 6;
    576                    buffer[pos++] = (byte) ((x >> 16) & MASK_8BITS);
    577                    break;
    578                case 3 :
    579                    buffer[pos++] = (byte) ((x >> 16) & MASK_8BITS);
    580                    buffer[pos++] = (byte) ((x >> 8) & MASK_8BITS);
    581                    break;
    582                default:
    583                    break;  // other values ignored
    584            }
    585        }
    586    }
    587
    588    /**
    589     * Returns whether or not the <code>octet</code> is in the base 64 alphabet.
    590     *
    591     * @param octet
    592     *            The value to test
    593     * @return <code>true</code> if the value is defined in the the base 64 alphabet, <code>false</code> otherwise.
    594     * @since 1.4
    595     */
    596    public static boolean isBase64(byte octet) {
    597        return octet == PAD || (octet >= 0 && octet < DECODE_TABLE.length && DECODE_TABLE[octet] != -1);
    598    }
    599
    600    /**
    601     * Tests a given byte array to see if it contains only valid characters within the Base64 alphabet. Currently the
    602     * method treats whitespace as valid.
    603     *
    604     * @param arrayOctet
    605     *            byte array to test
    606     * @return <code>true</code> if all bytes are valid characters in the Base64 alphabet or if the byte array is empty;
    607     *         false, otherwise
    608     */
    609    public static boolean isArrayByteBase64(byte[] arrayOctet) {
    610        for (int i = 0; i < arrayOctet.length; i++) {
    611            if (!isBase64(arrayOctet[i]) && !isWhiteSpace(arrayOctet[i])) {
    612                return false;
    613            }
    614        }
    615        return true;
    616    }
    617
    618    /**
    619     * Tests a given byte array to see if it contains only valid characters within the Base64 alphabet.
    620     *
    621     * @param arrayOctet
    622     *            byte array to test
    623     * @return <code>true</code> if any byte is a valid character in the Base64 alphabet; false herwise
    624     */
    625    private static boolean containsBase64Byte(byte[] arrayOctet) {
    626        for (byte element : arrayOctet)
    627        {
    628            if (isBase64(element)) {
    629                return true;
    630            }
    631        }
    632        return false;
    633    }
    634
    635    /**
    636     * Encodes binary data using the base64 algorithm but does not chunk the output.
    637     *
    638     * @param binaryData
    639     *            binary data to encode
    640     * @return byte[] containing Base64 characters in their UTF-8 representation.
    641     */
    642    public static byte[] encodeBase64(byte[] binaryData) {
    643        return encodeBase64(binaryData, false);
    644    }
    645
    646    /**
    647     * Encodes binary data using the base64 algorithm into 76 character blocks separated by CRLF.
    648     * <p>
    649     * For a non-chunking version, see {@link #encodeBase64StringUnChunked(byte[])}.
    650     *
    651     * @param binaryData
    652     *            binary data to encode
    653     * @return String containing Base64 characters.
    654     * @since 1.4
    655     */
    656    public static String encodeBase64String(byte[] binaryData) {
    657        return newStringUtf8(encodeBase64(binaryData, true));
    658    }
    659
    660    /**
    661     * Encodes binary data using the base64 algorithm, without using chunking.
    662     * <p>
    663     * For a chunking version, see {@link #encodeBase64String(byte[])}.
    664     *
    665     * @param binaryData
    666     *            binary data to encode
    667     * @return String containing Base64 characters.
    668     * @since 3.2
    669     */
    670    public static String encodeBase64StringUnChunked(byte[] binaryData) {
    671        return newStringUtf8(encodeBase64(binaryData, false));
    672    }
    673
    674    /**
    675     * Encodes binary data using the base64 algorithm.
    676     *
    677     * @param binaryData
    678     *            binary data to encode
    679     * @param useChunking whether to split the output into chunks
    680     * @return String containing Base64 characters.
    681     * @since 3.2
    682     */
    683    public static String encodeBase64String(byte[] binaryData, boolean useChunking) {
    684        return newStringUtf8(encodeBase64(binaryData, useChunking));
    685    }
    686
    687    /**
    688     * Encodes binary data using a URL-safe variation of the base64 algorithm but does not chunk the output. The
    689     * url-safe variation emits - and _ instead of + and / characters.
    690     *
    691     * @param binaryData
    692     *            binary data to encode
    693     * @return byte[] containing Base64 characters in their UTF-8 representation.
    694     * @since 1.4
    695     */
    696    public static byte[] encodeBase64URLSafe(byte[] binaryData) {
    697        return encodeBase64(binaryData, false, true);
    698    }
    699
    700    /**
    701     * Encodes binary data using a URL-safe variation of the base64 algorithm but does not chunk the output. The
    702     * url-safe variation emits - and _ instead of + and / characters.
    703     *
    704     * @param binaryData
    705     *            binary data to encode
    706     * @return String containing Base64 characters
    707     * @since 1.4
    708     */
    709    public static String encodeBase64URLSafeString(byte[] binaryData) {
    710        return newStringUtf8(encodeBase64(binaryData, false, true));
    711    }
    712
    713    /**
    714     * Encodes binary data using the base64 algorithm and chunks the encoded output into 76 character blocks
    715     *
    716     * @param binaryData
    717     *            binary data to encode
    718     * @return Base64 characters chunked in 76 character blocks
    719     */
    720    public static byte[] encodeBase64Chunked(byte[] binaryData) {
    721        return encodeBase64(binaryData, true);
    722    }
    723
    724    /**
    725     * Decodes a String containing containing characters in the Base64 alphabet.
    726     *
    727     * @param pArray
    728     *            A String containing Base64 character data
    729     * @return a byte array containing binary data
    730     * @since 1.4
    731     */
    732    public byte[] decode(String pArray) {
    733        return decode(getBytesUtf8(pArray));
    734    }
    735
    736    private byte[] getBytesUtf8(String pArray) {
    737        try {
    738            return pArray.getBytes("UTF8");
    739        } catch (UnsupportedEncodingException e) {
    740            throw new RuntimeException(e);
    741        }
    742    }
    743
    744    /**
    745     * Decodes a byte[] containing containing characters in the Base64 alphabet.
    746     *
    747     * @param pArray
    748     *            A byte array containing Base64 character data
    749     * @return a byte array containing binary data
    750     */
    751    public byte[] decode(byte[] pArray) {
    752        reset();
    753        if (pArray == null || pArray.length == 0) {
    754            return pArray;
    755        }
    756        long len = (pArray.length * 3) / 4;
    757        byte[] buf = new byte[(int) len];
    758        setInitialBuffer(buf, 0, buf.length);
    759        decode(pArray, 0, pArray.length);
    760        decode(pArray, 0, -1); // Notify decoder of EOF.
    761
    762        // Would be nice to just return buf (like we sometimes do in the encode
    763        // logic), but we have no idea what the line-length was (could even be
    764        // variable).  So we cannot determine ahead of time exactly how big an
    765        // array is necessary.  Hence the need to construct a 2nd byte array to
    766        // hold the final result:
    767
    768        byte[] result = new byte[pos];
    769        readResults(result, 0, result.length);
    770        return result;
    771    }
    772
    773    /**
    774     * Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks.
    775     *
    776     * @param binaryData
    777     *            Array containing binary data to encode.
    778     * @param isChunked
    779     *            if <code>true</code> this encoder will chunk the base64 output into 76 character blocks
    780     * @return Base64-encoded data.
    781     * @throws IllegalArgumentException
    782     *             Thrown when the input array needs an output array bigger than {@link Integer#MAX_VALUE}
    783     */
    784    public static byte[] encodeBase64(byte[] binaryData, boolean isChunked) {
    785        return encodeBase64(binaryData, isChunked, false);
    786    }
    787
    788    /**
    789     * Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks.
    790     *
    791     * @param binaryData
    792     *            Array containing binary data to encode.
    793     * @param isChunked
    794     *            if <code>true</code> this encoder will chunk the base64 output into 76 character blocks
    795     * @param urlSafe
    796     *            if <code>true</code> this encoder will emit - and _ instead of the usual + and / characters.
    797     * @return Base64-encoded data.
    798     * @throws IllegalArgumentException
    799     *             Thrown when the input array needs an output array bigger than {@link Integer#MAX_VALUE}
    800     * @since 1.4
    801     */
    802    public static byte[] encodeBase64(byte[] binaryData, boolean isChunked, boolean urlSafe) {
    803        return encodeBase64(binaryData, isChunked, urlSafe, Integer.MAX_VALUE);
    804    }
    805
    806    /**
    807     * Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks.
    808     *
    809     * @param binaryData
    810     *            Array containing binary data to encode.
    811     * @param isChunked
    812     *            if <code>true</code> this encoder will chunk the base64 output into 76 character blocks
    813     * @param urlSafe
    814     *            if <code>true</code> this encoder will emit - and _ instead of the usual + and / characters.
    815     * @param maxResultSize
    816     *            The maximum result size to accept.
    817     * @return Base64-encoded data.
    818     * @throws IllegalArgumentException
    819     *             Thrown when the input array needs an output array bigger than maxResultSize
    820     * @since 1.4
    821     */
    822    public static byte[] encodeBase64(byte[] binaryData, boolean isChunked, boolean urlSafe, int maxResultSize) {
    823        if (binaryData == null || binaryData.length == 0) {
    824            return binaryData;
    825        }
    826
    827        long len = getEncodeLength(binaryData, isChunked ? CHUNK_SIZE : 0, isChunked ? CHUNK_SEPARATOR : EMPTY_BYTE_ARRAY);
    828        if (len > maxResultSize) {
    829            throw new IllegalArgumentException("Input array too big, the output array would be bigger (" +
    830                len +
    831                ") than the specified maxium size of " +
    832                maxResultSize);
    833        }
    834
    835        Base64 b64 = isChunked ? new Base64(urlSafe) : new Base64(0, CHUNK_SEPARATOR, urlSafe);
    836        return b64.encode(binaryData);
    837    }
    838
    839    /**
    840     * Decodes a Base64 String into octets
    841     *
    842     * @param base64String
    843     *            String containing Base64 data
    844     * @return Array containing decoded data.
    845     * @since 1.4
    846     */
    847    public static byte[] decodeBase64(String base64String) {
    848        return new Base64().decode(base64String);
    849    }
    850
    851    /**
    852     * Decodes Base64 data into octets
    853     *
    854     * @param base64Data
    855     *            Byte array containing Base64 data
    856     * @return Array containing decoded data.
    857     */
    858    public static byte[] decodeBase64(byte[] base64Data) {
    859        return new Base64().decode(base64Data);
    860    }
    861
    862
    863
    864    /**
    865     * Checks if a byte value is whitespace or not.
    866     *
    867     * @param byteToCheck
    868     *            the byte to check
    869     * @return true if byte is whitespace, false otherwise
    870     */
    871    private static boolean isWhiteSpace(byte byteToCheck) {
    872        switch (byteToCheck) {
    873            case ' ' :
    874            case '\n' :
    875            case '\r' :
    876            case '\t' :
    877                return true;
    878            default :
    879                return false;
    880        }
    881    }
    882
    883    /**
    884     * Encodes a byte[] containing binary data, into a String containing characters in the Base64 alphabet.
    885     *
    886     * @param pArray
    887     *            a byte array containing binary data
    888     * @return A String containing only Base64 character data
    889     * @since 1.4
    890     */
    891    public String encodeToString(byte[] pArray) {
    892        return newStringUtf8(encode(pArray));
    893    }
    894
    895    private static String newStringUtf8(byte[] encode) {
    896        String str = null;
    897        try {
    898            str = new String(encode, "UTF8");
    899        } catch (UnsupportedEncodingException ue) {
    900            throw new RuntimeException(ue);
    901        }
    902        return str;
    903    }
    904
    905    /**
    906     * Encodes a byte[] containing binary data, into a byte[] containing characters in the Base64 alphabet.
    907     *
    908     * @param pArray
    909     *            a byte array containing binary data
    910     * @return A byte array containing only Base64 character data
    911     */
    912    public byte[] encode(byte[] pArray) {
    913        reset();
    914        if (pArray == null || pArray.length == 0) {
    915            return pArray;
    916        }
    917        long len = getEncodeLength(pArray, lineLength, lineSeparator);
    918        byte[] buf = new byte[(int) len];
    919        setInitialBuffer(buf, 0, buf.length);
    920        encode(pArray, 0, pArray.length);
    921        encode(pArray, 0, -1); // Notify encoder of EOF.
    922        // Encoder might have resized, even though it was unnecessary.
    923        if (buffer != buf) {
    924            readResults(buf, 0, buf.length);
    925        }
    926        // In URL-SAFE mode we skip the padding characters, so sometimes our
    927        // final length is a bit smaller.
    928        if (isUrlSafe() && pos < buf.length) {
    929            byte[] smallerBuf = new byte[pos];
    930            System.arraycopy(buf, 0, smallerBuf, 0, pos);
    931            buf = smallerBuf;
    932        }
    933        return buf;
    934    }
    935
    936    /**
    937     * Pre-calculates the amount of space needed to base64-encode the supplied array.
    938     *
    939     * @param pArray byte[] array which will later be encoded
    940     * @param chunkSize line-length of the output (<= 0 means no chunking) between each
    941     *        chunkSeparator (e.g. CRLF).
    942     * @param chunkSeparator the sequence of bytes used to separate chunks of output (e.g. CRLF).
    943     *
    944     * @return amount of space needed to encoded the supplied array.  Returns
    945     *         a long since a max-len array will require Integer.MAX_VALUE + 33%.
    946     */
    947    private static long getEncodeLength(byte[] pArray, int chunkSize, byte[] chunkSeparator) {
    948        // base64 always encodes to multiples of 4.
    949        chunkSize = (chunkSize / 4) * 4;
    950
    951        long len = (pArray.length * 4) / 3;
    952        long mod = len % 4;
    953        if (mod != 0) {
    954            len += 4 - mod;
    955        }
    956        if (chunkSize > 0) {
    957            boolean lenChunksPerfectly = len % chunkSize == 0;
    958            len += (len / chunkSize) * chunkSeparator.length;
    959            if (!lenChunksPerfectly) {
    960                len += chunkSeparator.length;
    961            }
    962        }
    963        return len;
    964    }
    965
    966    // Implementation of integer encoding used for crypto
    967    /**
    968     * Decodes a byte64-encoded integer according to crypto standards such as W3C's XML-Signature
    969     *
    970     * @param pArray
    971     *            a byte array containing base64 character data
    972     * @return A BigInteger
    973     * @since 1.4
    974     */
    975    public static BigInteger decodeInteger(byte[] pArray) {
    976        return new BigInteger(1, decodeBase64(pArray));
    977    }
    978
    979    /**
    980     * Encodes to a byte64-encoded integer according to crypto standards such as W3C's XML-Signature
    981     *
    982     * @param bigInt
    983     *            a BigInteger
    984     * @return A byte array containing base64 character data
    985     * @throws NullPointerException
    986     *             if null is passed in
    987     * @since 1.4
    988     */
    989    public static byte[] encodeInteger(BigInteger bigInt) {
    990        if (bigInt == null) {
    991            throw new NullPointerException("encodeInteger called with null parameter");
    992        }
    993        return encodeBase64(toIntegerBytes(bigInt), false);
    994    }
    995
    996    /**
    997     * Returns a byte-array representation of a <code>BigInteger</code> without sign bit.
    998     *
    999     * @param bigInt
    1000     *            <code>BigInteger</code> to be converted
    1001     * @return a byte array representation of the BigInteger parameter
    1002     */
    1003    static byte[] toIntegerBytes(BigInteger bigInt) {
    1004        int bitlen = bigInt.bitLength();
    1005        // round bitlen
    1006        bitlen = ((bitlen + 7) >> 3) << 3;
    1007        byte[] bigBytes = bigInt.toByteArray();
    1008
    1009        if (((bigInt.bitLength() % 8) != 0) && (((bigInt.bitLength() / 8) + 1) == (bitlen / 8))) {
    1010            return bigBytes;
    1011        }
    1012        // set up params for copying everything but sign bit
    1013        int startSrc = 0;
    1014        int len = bigBytes.length;
    1015
    1016        // if bigInt is exactly byte-aligned, just skip signbit in copy
    1017        if ((bigInt.bitLength() % 8) == 0) {
    1018            startSrc = 1;
    1019            len--;
    1020        }
    1021        int startDst = bitlen / 8 - len; // to pad w/ nulls as per spec
    1022        byte[] resizedBytes = new byte[bitlen / 8];
    1023        System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, len);
    1024        return resizedBytes;
    1025    }
    1026
    1027    /**
    1028     * Resets this Base64 object to its initial newly constructed state.
    1029     */
    1030    private void reset() {
    1031        buffer = null;
    1032        pos = 0;
    1033        readPos = 0;
    1034        currentLinePos = 0;
    1035        modulus = 0;
    1036        eof = false;
    1037    }
    1038
    1039    // Getters for use in testing
    1040
    1041    int getLineLength() {
    1042        return lineLength;
    1043    }
    1044
    1045    byte[] getLineSeparator() {
    1046        return lineSeparator.clone();
    1047    }
    1048}