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