View Javadoc
1   package org.codehaus.plexus.util;
2   
3   /*
4    * Copyright The Codehaus Foundation.
5    *
6    * Licensed under the Apache License, Version 2.0 (the "License");
7    * you may not use this file except in compliance with the License.
8    * You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  
19  /**
20   * Provides Base64 encoding and decoding as defined by RFC 2045.
21   * <p>
22   * This class implements section <cite>6.8. Base64 Content-Transfer-Encoding</cite> from RFC 2045 <cite>Multipurpose
23   * Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies</cite> by Freed and Borenstein.
24   * </p>
25   *
26   * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>
27   * @author Apache Software Foundation
28   * @since 1.0-dev
29   *
30   */
31  public class Base64 {
32  
33      //
34      // Source Id: Base64.java 161350 2005-04-14 20:39:46Z ggregory
35      //
36  
37      /**
38       * Chunk size per RFC 2045 section 6.8.
39       * <p>
40       * The {@value} character limit does not count the trailing CRLF, but counts all other characters, including any
41       * equal signs.
42       * </p>
43       *
44       * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 6.8</a>
45       */
46      static final int CHUNK_SIZE = 76;
47  
48      /**
49       * Chunk separator per RFC 2045 section 2.1.
50       *
51       * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 2.1</a>
52       */
53      static final byte[] CHUNK_SEPARATOR = "\r\n".getBytes();
54  
55      /**
56       * The base length.
57       */
58      static final int BASELENGTH = 255;
59  
60      /**
61       * Lookup length.
62       */
63      static final int LOOKUPLENGTH = 64;
64  
65      /**
66       * Used to calculate the number of bits in a byte.
67       */
68      static final int EIGHTBIT = 8;
69  
70      /**
71       * Used when encoding something which has fewer than 24 bits.
72       */
73      static final int SIXTEENBIT = 16;
74  
75      /**
76       * Used to determine how many bits data contains.
77       */
78      static final int TWENTYFOURBITGROUP = 24;
79  
80      /**
81       * Used to get the number of Quadruples.
82       */
83      static final int FOURBYTE = 4;
84  
85      /**
86       * Used to test the sign of a byte.
87       */
88      static final int SIGN = -128;
89  
90      /**
91       * Byte used to pad output.
92       */
93      static final byte PAD = (byte) '=';
94  
95      /**
96       * Contains the Base64 values <code>0</code> through <code>63</code> accessed by using character encodings as
97       * indices.
98       * <p>
99       * For example, <code>base64Alphabet['+']</code> returns <code>62</code>.
100      * </p>
101      * <p>
102      * The value of undefined encodings is <code>-1</code>.
103      * </p>
104      */
105     private static byte[] base64Alphabet = new byte[BASELENGTH];
106 
107     /**
108      * <p>
109      * Contains the Base64 encodings <code>A</code> through <code>Z</code>, followed by <code>a</code> through
110      * <code>z</code>, followed by <code>0</code> through <code>9</code>, followed by <code>+</code>, and
111      * <code>/</code>.
112      * </p>
113      * <p>
114      * This array is accessed by using character values as indices.
115      * </p>
116      * <p>
117      * For example, <code>lookUpBase64Alphabet[62] </code> returns <code>'+'</code>.
118      * </p>
119      */
120     private static byte[] lookUpBase64Alphabet = new byte[LOOKUPLENGTH];
121 
122     // Populating the lookup and character arrays
123     static {
124         for (int i = 0; i < BASELENGTH; i++) {
125             base64Alphabet[i] = (byte) -1;
126         }
127         for (int i = 'Z'; i >= 'A'; i--) {
128             base64Alphabet[i] = (byte) (i - 'A');
129         }
130         for (int i = 'z'; i >= 'a'; i--) {
131             base64Alphabet[i] = (byte) (i - 'a' + 26);
132         }
133         for (int i = '9'; i >= '0'; i--) {
134             base64Alphabet[i] = (byte) (i - '0' + 52);
135         }
136 
137         base64Alphabet['+'] = 62;
138         base64Alphabet['/'] = 63;
139 
140         for (int i = 0; i <= 25; i++) {
141             lookUpBase64Alphabet[i] = (byte) ('A' + i);
142         }
143 
144         for (int i = 26, j = 0; i <= 51; i++, j++) {
145             lookUpBase64Alphabet[i] = (byte) ('a' + j);
146         }
147 
148         for (int i = 52, j = 0; i <= 61; i++, j++) {
149             lookUpBase64Alphabet[i] = (byte) ('0' + j);
150         }
151 
152         lookUpBase64Alphabet[62] = (byte) '+';
153         lookUpBase64Alphabet[63] = (byte) '/';
154     }
155 
156     /**
157      * Returns whether or not the <code>octect</code> is in the base 64 alphabet.
158      *
159      * @param octect The value to test
160      * @return <code>true</code> if the value is defined in the the base 64 alphabet, <code>false</code> otherwise.
161      */
162     private static boolean isBase64(byte octect) {
163         if (octect == PAD) {
164             return true;
165         } else if (octect < 0 || base64Alphabet[octect] == -1) {
166             return false;
167         } else {
168             return true;
169         }
170     }
171 
172     /**
173      * Tests a given byte array to see if it contains only valid characters within the Base64 alphabet.
174      *
175      * @param arrayOctect byte array to test
176      * @return <code>true</code> if all bytes are valid characters in the Base64 alphabet or if the byte array is empty;
177      *         false, otherwise
178      */
179     public static boolean isArrayByteBase64(byte[] arrayOctect) {
180 
181         arrayOctect = discardWhitespace(arrayOctect);
182 
183         int length = arrayOctect.length;
184         if (length == 0) {
185             // shouldn't a 0 length array be valid base64 data?
186             // return false;
187             return true;
188         }
189         for (byte anArrayOctect : arrayOctect) {
190             if (!isBase64(anArrayOctect)) {
191                 return false;
192             }
193         }
194         return true;
195     }
196 
197     /**
198      * Encodes binary data using the base64 algorithm but does not chunk the output.
199      *
200      * @param binaryData binary data to encode
201      * @return Base64 characters
202      */
203     public static byte[] encodeBase64(byte[] binaryData) {
204         return encodeBase64(binaryData, false);
205     }
206 
207     /**
208      * Encodes binary data using the base64 algorithm and chunks the encoded output into 76 character blocks
209      *
210      * @param binaryData binary data to encode
211      * @return Base64 characters chunked in 76 character blocks
212      */
213     public static byte[] encodeBase64Chunked(byte[] binaryData) {
214         return encodeBase64(binaryData, true);
215     }
216 
217     /**
218      * Decodes a byte[] containing containing characters in the Base64 alphabet.
219      *
220      * @param pArray A byte array containing Base64 character data
221      * @return a byte array containing binary data
222      */
223     public byte[] decode(byte[] pArray) {
224         return decodeBase64(pArray);
225     }
226 
227     /**
228      * Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks.
229      *
230      * @param binaryData Array containing binary data to encode.
231      * @param isChunked if <code>true</code> this encoder will chunk the base64 output into 76 character blocks
232      * @return Base64-encoded data.
233      */
234     public static byte[] encodeBase64(byte[] binaryData, boolean isChunked) {
235         int lengthDataBits = binaryData.length * EIGHTBIT;
236         int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;
237         int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;
238         byte encodedData[] = null;
239         int encodedDataLength = 0;
240         int nbrChunks = 0;
241 
242         if (fewerThan24bits != 0) {
243             // data not divisible by 24 bit
244             encodedDataLength = (numberTriplets + 1) * 4;
245         } else {
246             // 16 or 8 bit
247             encodedDataLength = numberTriplets * 4;
248         }
249 
250         // If the output is to be "chunked" into 76 character sections,
251         // for compliance with RFC 2045 MIME, then it is important to
252         // allow for extra length to account for the separator(s)
253         if (isChunked) {
254 
255             nbrChunks = (CHUNK_SEPARATOR.length == 0 ? 0 : (int) Math.ceil((float) encodedDataLength / CHUNK_SIZE));
256             encodedDataLength += nbrChunks * CHUNK_SEPARATOR.length;
257         }
258 
259         encodedData = new byte[encodedDataLength];
260 
261         byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;
262 
263         int encodedIndex = 0;
264         int dataIndex = 0;
265         int i = 0;
266         int nextSeparatorIndex = CHUNK_SIZE;
267         int chunksSoFar = 0;
268 
269         // log.debug("number of triplets = " + numberTriplets);
270         for (i = 0; i < numberTriplets; i++) {
271             dataIndex = i * 3;
272             b1 = binaryData[dataIndex];
273             b2 = binaryData[dataIndex + 1];
274             b3 = binaryData[dataIndex + 2];
275 
276             // log.debug("b1= " + b1 +", b2= " + b2 + ", b3= " + b3);
277 
278             l = (byte) (b2 & 0x0f);
279             k = (byte) (b1 & 0x03);
280 
281             byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
282             byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
283             byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6) : (byte) ((b3) >> 6 ^ 0xfc);
284 
285             encodedData[encodedIndex] = lookUpBase64Alphabet[val1];
286             // log.debug( "val2 = " + val2 );
287             // log.debug( "k4 = " + (k<<4) );
288             // log.debug( "vak = " + (val2 | (k<<4)) );
289             encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)];
290             encodedData[encodedIndex + 2] = lookUpBase64Alphabet[(l << 2) | val3];
291             encodedData[encodedIndex + 3] = lookUpBase64Alphabet[b3 & 0x3f];
292 
293             encodedIndex += 4;
294 
295             // If we are chunking, let's put a chunk separator down.
296             if (isChunked) {
297                 // this assumes that CHUNK_SIZE % 4 == 0
298                 if (encodedIndex == nextSeparatorIndex) {
299                     System.arraycopy(CHUNK_SEPARATOR, 0, encodedData, encodedIndex, CHUNK_SEPARATOR.length);
300                     chunksSoFar++;
301                     nextSeparatorIndex = (CHUNK_SIZE * (chunksSoFar + 1)) + (chunksSoFar * CHUNK_SEPARATOR.length);
302                     encodedIndex += CHUNK_SEPARATOR.length;
303                 }
304             }
305         }
306 
307         // form integral number of 6-bit groups
308         dataIndex = i * 3;
309 
310         if (fewerThan24bits == EIGHTBIT) {
311             b1 = binaryData[dataIndex];
312             k = (byte) (b1 & 0x03);
313             // log.debug("b1=" + b1);
314             // log.debug("b1<<2 = " + (b1>>2) );
315             byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
316             encodedData[encodedIndex] = lookUpBase64Alphabet[val1];
317             encodedData[encodedIndex + 1] = lookUpBase64Alphabet[k << 4];
318             encodedData[encodedIndex + 2] = PAD;
319             encodedData[encodedIndex + 3] = PAD;
320         } else if (fewerThan24bits == SIXTEENBIT) {
321 
322             b1 = binaryData[dataIndex];
323             b2 = binaryData[dataIndex + 1];
324             l = (byte) (b2 & 0x0f);
325             k = (byte) (b1 & 0x03);
326 
327             byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
328             byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
329 
330             encodedData[encodedIndex] = lookUpBase64Alphabet[val1];
331             encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)];
332             encodedData[encodedIndex + 2] = lookUpBase64Alphabet[l << 2];
333             encodedData[encodedIndex + 3] = PAD;
334         }
335 
336         if (isChunked) {
337             // we also add a separator to the end of the final chunk.
338             if (chunksSoFar < nbrChunks) {
339                 System.arraycopy(
340                         CHUNK_SEPARATOR,
341                         0,
342                         encodedData,
343                         encodedDataLength - CHUNK_SEPARATOR.length,
344                         CHUNK_SEPARATOR.length);
345             }
346         }
347 
348         return encodedData;
349     }
350 
351     /**
352      * Decodes Base64 data into octects
353      *
354      * @param base64Data Byte array containing Base64 data
355      * @return Array containing decoded data.
356      */
357     public static byte[] decodeBase64(byte[] base64Data) {
358         // RFC 2045 requires that we discard ALL non-Base64 characters
359         base64Data = discardNonBase64(base64Data);
360 
361         // handle the edge case, so we don't have to worry about it later
362         if (base64Data.length == 0) {
363             return new byte[0];
364         }
365 
366         int numberQuadruple = base64Data.length / FOURBYTE;
367         byte decodedData[] = null;
368         byte b1 = 0, b2 = 0, b3 = 0, b4 = 0, marker0 = 0, marker1 = 0;
369 
370         // Throw away anything not in base64Data
371 
372         int encodedIndex = 0;
373         int dataIndex = 0;
374         {
375             // this sizes the output array properly - rlw
376             int lastData = base64Data.length;
377             // ignore the '=' padding
378             while (base64Data[lastData - 1] == PAD) {
379                 if (--lastData == 0) {
380                     return new byte[0];
381                 }
382             }
383             decodedData = new byte[lastData - numberQuadruple];
384         }
385 
386         for (int i = 0; i < numberQuadruple; i++) {
387             dataIndex = i * 4;
388             marker0 = base64Data[dataIndex + 2];
389             marker1 = base64Data[dataIndex + 3];
390 
391             b1 = base64Alphabet[base64Data[dataIndex]];
392             b2 = base64Alphabet[base64Data[dataIndex + 1]];
393 
394             if (marker0 != PAD && marker1 != PAD) {
395                 // No PAD e.g 3cQl
396                 b3 = base64Alphabet[marker0];
397                 b4 = base64Alphabet[marker1];
398 
399                 decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
400                 decodedData[encodedIndex + 1] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
401                 decodedData[encodedIndex + 2] = (byte) (b3 << 6 | b4);
402             } else if (marker0 == PAD) {
403                 // Two PAD e.g. 3c[Pad][Pad]
404                 decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
405             } else if (marker1 == PAD) {
406                 // One PAD e.g. 3cQ[Pad]
407                 b3 = base64Alphabet[marker0];
408 
409                 decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
410                 decodedData[encodedIndex + 1] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
411             }
412             encodedIndex += 3;
413         }
414         return decodedData;
415     }
416 
417     /**
418      * Discards any whitespace from a base-64 encoded block.
419      *
420      * @param data The base-64 encoded data to discard the whitespace from.
421      * @return The data, less whitespace (see RFC 2045).
422      */
423     static byte[] discardWhitespace(byte[] data) {
424         byte groomedData[] = new byte[data.length];
425         int bytesCopied = 0;
426 
427         for (byte aData : data) {
428             switch (aData) {
429                 case (byte) ' ':
430                 case (byte) '\n':
431                 case (byte) '\r':
432                 case (byte) '\t':
433                     break;
434                 default:
435                     groomedData[bytesCopied++] = aData;
436             }
437         }
438 
439         byte packedData[] = new byte[bytesCopied];
440 
441         System.arraycopy(groomedData, 0, packedData, 0, bytesCopied);
442 
443         return packedData;
444     }
445 
446     /**
447      * Discards any characters outside of the base64 alphabet, per the requirements on page 25 of RFC 2045 - "Any
448      * characters outside of the base64 alphabet are to be ignored in base64 encoded data."
449      *
450      * @param data The base-64 encoded data to groom
451      * @return The data, less non-base64 characters (see RFC 2045).
452      */
453     static byte[] discardNonBase64(byte[] data) {
454         byte groomedData[] = new byte[data.length];
455         int bytesCopied = 0;
456 
457         for (byte aData : data) {
458             if (isBase64(aData)) {
459                 groomedData[bytesCopied++] = aData;
460             }
461         }
462 
463         byte packedData[] = new byte[bytesCopied];
464 
465         System.arraycopy(groomedData, 0, packedData, 0, bytesCopied);
466 
467         return packedData;
468     }
469 
470     /**
471      * Encodes a byte[] containing binary data, into a byte[] containing characters in the Base64 alphabet.
472      *
473      * @param pArray a byte array containing binary data
474      * @return A byte array containing only Base64 character data
475      */
476     public byte[] encode(byte[] pArray) {
477         return encodeBase64(pArray, false);
478     }
479 }