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