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