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: */package org.apache.openejb.util;
017:
018: import java.io.IOException;
019:
020: /**
021: * Provides Base64 encoding and decoding as defined by RFC 2045.
022: *
023: * <p>This class implements section <cite>6.8. Base64 Content-Transfer-Encoding</cite>
024: * from RFC 2045 <cite>Multipurpose Internet Mail Extensions (MIME) Part One:
025: * Format of Internet Message Bodies</cite> by Freed and Borenstein.</p>
026: *
027: * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>
028: * @author Apache Software Foundation
029: * @since 1.0-dev
030: * @version $Id: Base64.java 602704 2007-12-09 17:58:22Z jlaskowski $
031: */
032: public class Base64 {
033:
034: /**
035: * Chunk size per RFC 2045 section 6.8.
036: *
037: * <p>The {@value} character limit does not count the trailing CRLF, but counts
038: * all other characters, including any equal signs.</p>
039: *
040: * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 6.8</a>
041: */
042: static final int CHUNK_SIZE = 76;
043:
044: /**
045: * Chunk separator per RFC 2045 section 2.1.
046: *
047: * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 2.1</a>
048: */
049: static final byte[] CHUNK_SEPARATOR = "\r\n".getBytes();
050:
051: /**
052: * The base length.
053: */
054: static final int BASELENGTH = 255;
055:
056: /**
057: * Lookup length.
058: */
059: static final int LOOKUPLENGTH = 64;
060:
061: /**
062: * Used to calculate the number of bits in a byte.
063: */
064: static final int EIGHTBIT = 8;
065:
066: /**
067: * Used when encoding something which has fewer than 24 bits.
068: */
069: static final int SIXTEENBIT = 16;
070:
071: /**
072: * Used to determine how many bits data contains.
073: */
074: static final int TWENTYFOURBITGROUP = 24;
075:
076: /**
077: * Used to get the number of Quadruples.
078: */
079: static final int FOURBYTE = 4;
080:
081: /**
082: * Used to test the sign of a byte.
083: */
084: static final int SIGN = -128;
085:
086: /**
087: * Byte used to pad output.
088: */
089: static final byte PAD = (byte) '=';
090:
091: /**
092: * Contains the Base64 values <code>0</code> through <code>63</code> accessed by using character encodings as
093: * indices.
094: * <p>
095: * For example, <code>base64Alphabet['+']</code> returns <code>62</code>.
096: * </p>
097: * <p>
098: * The value of undefined encodings is <code>-1</code>.
099: * </p>
100: */
101: private static byte[] base64Alphabet = new byte[BASELENGTH];
102:
103: /**
104: * <p>
105: * Contains the Base64 encodings <code>A</code> through <code>Z</code>, followed by <code>a</code> through
106: * <code>z</code>, followed by <code>0</code> through <code>9</code>, followed by <code>+</code>, and
107: * <code>/</code>.
108: * </p>
109: * <p>
110: * This array is accessed by using character values as indices.
111: * </p>
112: * <p>
113: * For example, <code>lookUpBase64Alphabet[62] </code> returns <code>'+'</code>.
114: * </p>
115: */
116: private static byte[] lookUpBase64Alphabet = new byte[LOOKUPLENGTH];
117:
118: // Populating the lookup and character arrays
119: static {
120: for (int i = 0; i < BASELENGTH; i++) {
121: base64Alphabet[i] = (byte) -1;
122: }
123: for (int i = 'Z'; i >= 'A'; i--) {
124: base64Alphabet[i] = (byte) (i - 'A');
125: }
126: for (int i = 'z'; i >= 'a'; i--) {
127: base64Alphabet[i] = (byte) (i - 'a' + 26);
128: }
129: for (int i = '9'; i >= '0'; i--) {
130: base64Alphabet[i] = (byte) (i - '0' + 52);
131: }
132:
133: base64Alphabet['+'] = 62;
134: base64Alphabet['/'] = 63;
135:
136: for (int i = 0; i <= 25; i++) {
137: lookUpBase64Alphabet[i] = (byte) ('A' + i);
138: }
139:
140: for (int i = 26, j = 0; i <= 51; i++, j++) {
141: lookUpBase64Alphabet[i] = (byte) ('a' + j);
142: }
143:
144: for (int i = 52, j = 0; i <= 61; i++, j++) {
145: lookUpBase64Alphabet[i] = (byte) ('0' + j);
146: }
147:
148: lookUpBase64Alphabet[62] = (byte) '+';
149: lookUpBase64Alphabet[63] = (byte) '/';
150: }
151:
152: /**
153: * Returns whether or not the <code>octect</code> is in the base 64 alphabet.
154: *
155: * @param octect The value to test
156: * @return <code>true</code> if the value is defined in the the base 64 alphabet, <code>false</code> otherwise.
157: */
158: private static boolean isBase64(byte octect) {
159: if (octect == PAD) {
160: return true;
161: } else if (octect < 0 || base64Alphabet[octect] == -1) {
162: return false;
163: } else {
164: return true;
165: }
166: }
167:
168: /**
169: * Tests a given byte array to see if it contains
170: * only valid characters within the Base64 alphabet.
171: *
172: * @param arrayOctect byte array to test
173: * @return <code>true</code> if all bytes are valid characters in the Base64
174: * alphabet or if the byte array is empty; false, otherwise
175: */
176: public static boolean isArrayByteBase64(byte[] arrayOctect) {
177:
178: arrayOctect = discardWhitespace(arrayOctect);
179:
180: int length = arrayOctect.length;
181: if (length == 0) {
182: // shouldn't a 0 length array be valid base64 data?
183: // return false;
184: return true;
185: }
186: for (int i = 0; i < length; i++) {
187: if (!isBase64(arrayOctect[i])) {
188: return false;
189: }
190: }
191: return true;
192: }
193:
194: /**
195: * Encodes binary data using the base64 algorithm but
196: * does not chunk the output.
197: *
198: * @param binaryData binary data to encode
199: * @return Base64 characters
200: */
201: public static byte[] encodeBase64(byte[] binaryData) {
202: return encodeBase64(binaryData, false);
203: }
204:
205: /**
206: * Encodes binary data using the base64 algorithm and chunks
207: * the encoded output into 76 character blocks
208: *
209: * @param binaryData binary data to encode
210: * @return Base64 characters chunked in 76 character blocks
211: */
212: public static byte[] encodeBase64Chunked(byte[] binaryData) {
213: return encodeBase64(binaryData, true);
214: }
215:
216: /**
217: * Decodes an Object using the base64 algorithm. This method
218: * is provided in order to satisfy the requirements of the
219: * Decoder interface, and will throw a DecoderException if the
220: * supplied object is not of type byte[].
221: *
222: * @param pObject Object to decode
223: * @return An object (of type byte[]) containing the
224: * binary data which corresponds to the byte[] supplied.
225: * @throws IOException if the parameter supplied is not
226: * of type byte[]
227: */
228: public Object decode(Object pObject) throws IOException {
229: if (!(pObject instanceof byte[])) {
230: throw new IOException(
231: "Parameter supplied to Base64 decode is not a byte[]");
232: }
233: return decode((byte[]) pObject);
234: }
235:
236: /**
237: * Decodes a byte[] containing containing
238: * characters in the Base64 alphabet.
239: *
240: * @param pArray A byte array containing Base64 character data
241: * @return a byte array containing binary data
242: */
243: public byte[] decode(byte[] pArray) {
244: return decodeBase64(pArray);
245: }
246:
247: /**
248: * Encodes binary data using the base64 algorithm, optionally
249: * chunking the output into 76 character blocks.
250: *
251: * @param binaryData Array containing binary data to encode.
252: * @param isChunked if <code>true</code> this encoder will chunk
253: * the base64 output into 76 character blocks
254: * @return Base64-encoded data.
255: */
256: public static byte[] encodeBase64(byte[] binaryData,
257: boolean isChunked) {
258: int lengthDataBits = binaryData.length * EIGHTBIT;
259: int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;
260: int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;
261: byte encodedData[] = null;
262: int encodedDataLength = 0;
263: int nbrChunks = 0;
264:
265: if (fewerThan24bits != 0) {
266: //data not divisible by 24 bit
267: encodedDataLength = (numberTriplets + 1) * 4;
268: } else {
269: // 16 or 8 bit
270: encodedDataLength = numberTriplets * 4;
271: }
272:
273: // If the output is to be "chunked" into 76 character sections,
274: // for compliance with RFC 2045 MIME, then it is important to
275: // allow for extra length to account for the separator(s)
276: if (isChunked) {
277:
278: nbrChunks = (CHUNK_SEPARATOR.length == 0 ? 0 : (int) Math
279: .ceil((float) encodedDataLength / CHUNK_SIZE));
280: encodedDataLength += nbrChunks * CHUNK_SEPARATOR.length;
281: }
282:
283: encodedData = new byte[encodedDataLength];
284:
285: byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;
286:
287: int encodedIndex = 0;
288: int dataIndex = 0;
289: int i = 0;
290: int nextSeparatorIndex = CHUNK_SIZE;
291: int chunksSoFar = 0;
292:
293: //log.debug("number of triplets = " + numberTriplets);
294: for (i = 0; i < numberTriplets; i++) {
295: dataIndex = i * 3;
296: b1 = binaryData[dataIndex];
297: b2 = binaryData[dataIndex + 1];
298: b3 = binaryData[dataIndex + 2];
299:
300: //log.debug("b1= " + b1 +", b2= " + b2 + ", b3= " + b3);
301:
302: l = (byte) (b2 & 0x0f);
303: k = (byte) (b1 & 0x03);
304:
305: byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2)
306: : (byte) ((b1) >> 2 ^ 0xc0);
307: byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4)
308: : (byte) ((b2) >> 4 ^ 0xf0);
309: byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6)
310: : (byte) ((b3) >> 6 ^ 0xfc);
311:
312: encodedData[encodedIndex] = lookUpBase64Alphabet[val1];
313: //log.debug( "val2 = " + val2 );
314: //log.debug( "k4 = " + (k<<4) );
315: //log.debug( "vak = " + (val2 | (k<<4)) );
316: encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2
317: | (k << 4)];
318: encodedData[encodedIndex + 2] = lookUpBase64Alphabet[(l << 2)
319: | val3];
320: encodedData[encodedIndex + 3] = lookUpBase64Alphabet[b3 & 0x3f];
321:
322: encodedIndex += 4;
323:
324: // If we are chunking, let's put a chunk separator down.
325: if (isChunked) {
326: // this assumes that CHUNK_SIZE % 4 == 0
327: if (encodedIndex == nextSeparatorIndex) {
328: System.arraycopy(CHUNK_SEPARATOR, 0, encodedData,
329: encodedIndex, CHUNK_SEPARATOR.length);
330: chunksSoFar++;
331: nextSeparatorIndex = (CHUNK_SIZE * (chunksSoFar + 1))
332: + (chunksSoFar * CHUNK_SEPARATOR.length);
333: encodedIndex += CHUNK_SEPARATOR.length;
334: }
335: }
336: }
337:
338: // form integral number of 6-bit groups
339: dataIndex = i * 3;
340:
341: if (fewerThan24bits == EIGHTBIT) {
342: b1 = binaryData[dataIndex];
343: k = (byte) (b1 & 0x03);
344: //log.debug("b1=" + b1);
345: //log.debug("b1<<2 = " + (b1>>2) );
346: byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2)
347: : (byte) ((b1) >> 2 ^ 0xc0);
348: encodedData[encodedIndex] = lookUpBase64Alphabet[val1];
349: encodedData[encodedIndex + 1] = lookUpBase64Alphabet[k << 4];
350: encodedData[encodedIndex + 2] = PAD;
351: encodedData[encodedIndex + 3] = PAD;
352: } else if (fewerThan24bits == SIXTEENBIT) {
353:
354: b1 = binaryData[dataIndex];
355: b2 = binaryData[dataIndex + 1];
356: l = (byte) (b2 & 0x0f);
357: k = (byte) (b1 & 0x03);
358:
359: byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2)
360: : (byte) ((b1) >> 2 ^ 0xc0);
361: byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4)
362: : (byte) ((b2) >> 4 ^ 0xf0);
363:
364: encodedData[encodedIndex] = lookUpBase64Alphabet[val1];
365: encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2
366: | (k << 4)];
367: encodedData[encodedIndex + 2] = lookUpBase64Alphabet[l << 2];
368: encodedData[encodedIndex + 3] = PAD;
369: }
370:
371: if (isChunked) {
372: // we also add a separator to the end of the final chunk.
373: if (chunksSoFar < nbrChunks) {
374: System.arraycopy(CHUNK_SEPARATOR, 0, encodedData,
375: encodedDataLength - CHUNK_SEPARATOR.length,
376: CHUNK_SEPARATOR.length);
377: }
378: }
379:
380: return encodedData;
381: }
382:
383: /**
384: * Decodes Base64 data into octects
385: *
386: * @param base64Data Byte array containing Base64 data
387: * @return Array containing decoded data.
388: */
389: public static byte[] decodeBase64(byte[] base64Data) {
390: // RFC 2045 requires that we discard ALL non-Base64 characters
391: base64Data = discardNonBase64(base64Data);
392:
393: // handle the edge case, so we don't have to worry about it later
394: if (base64Data.length == 0) {
395: return new byte[0];
396: }
397:
398: int numberQuadruple = base64Data.length / FOURBYTE;
399: byte decodedData[] = null;
400: byte b1 = 0, b2 = 0, b3 = 0, b4 = 0, marker0 = 0, marker1 = 0;
401:
402: // Throw away anything not in base64Data
403:
404: int encodedIndex = 0;
405: int dataIndex = 0;
406: {
407: // this sizes the output array properly - rlw
408: int lastData = base64Data.length;
409: // ignore the '=' padding
410: while (base64Data[lastData - 1] == PAD) {
411: if (--lastData == 0) {
412: return new byte[0];
413: }
414: }
415: decodedData = new byte[lastData - numberQuadruple];
416: }
417:
418: for (int i = 0; i < numberQuadruple; i++) {
419: dataIndex = i * 4;
420: marker0 = base64Data[dataIndex + 2];
421: marker1 = base64Data[dataIndex + 3];
422:
423: b1 = base64Alphabet[base64Data[dataIndex]];
424: b2 = base64Alphabet[base64Data[dataIndex + 1]];
425:
426: if (marker0 != PAD && marker1 != PAD) {
427: //No PAD e.g 3cQl
428: b3 = base64Alphabet[marker0];
429: b4 = base64Alphabet[marker1];
430:
431: decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
432: decodedData[encodedIndex + 1] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
433: decodedData[encodedIndex + 2] = (byte) (b3 << 6 | b4);
434: } else if (marker0 == PAD) {
435: //Two PAD e.g. 3c[Pad][Pad]
436: decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
437: } else if (marker1 == PAD) {
438: //One PAD e.g. 3cQ[Pad]
439: b3 = base64Alphabet[marker0];
440:
441: decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
442: decodedData[encodedIndex + 1] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
443: }
444: encodedIndex += 3;
445: }
446: return decodedData;
447: }
448:
449: /**
450: * Discards any whitespace from a base-64 encoded block.
451: *
452: * @param data The base-64 encoded data to discard the whitespace
453: * from.
454: * @return The data, less whitespace (see RFC 2045).
455: */
456: static byte[] discardWhitespace(byte[] data) {
457: byte groomedData[] = new byte[data.length];
458: int bytesCopied = 0;
459:
460: for (int i = 0; i < data.length; i++) {
461: switch (data[i]) {
462: case (byte) ' ':
463: case (byte) '\n':
464: case (byte) '\r':
465: case (byte) '\t':
466: break;
467: default:
468: groomedData[bytesCopied++] = data[i];
469: }
470: }
471:
472: byte packedData[] = new byte[bytesCopied];
473:
474: System.arraycopy(groomedData, 0, packedData, 0, bytesCopied);
475:
476: return packedData;
477: }
478:
479: /**
480: * Discards any characters outside of the base64 alphabet, per
481: * the requirements on page 25 of RFC 2045 - "Any characters
482: * outside of the base64 alphabet are to be ignored in base64
483: * encoded data."
484: *
485: * @param data The base-64 encoded data to groom
486: * @return The data, less non-base64 characters (see RFC 2045).
487: */
488: static byte[] discardNonBase64(byte[] data) {
489: byte groomedData[] = new byte[data.length];
490: int bytesCopied = 0;
491:
492: for (int i = 0; i < data.length; i++) {
493: if (isBase64(data[i])) {
494: groomedData[bytesCopied++] = data[i];
495: }
496: }
497:
498: byte packedData[] = new byte[bytesCopied];
499:
500: System.arraycopy(groomedData, 0, packedData, 0, bytesCopied);
501:
502: return packedData;
503: }
504:
505: // Implementation of the Encoder Interface
506:
507: /**
508: * Encodes an Object using the base64 algorithm. This method
509: * is provided in order to satisfy the requirements of the
510: * Encoder interface, and will throw an EncoderException if the
511: * supplied object is not of type byte[].
512: *
513: * @param pObject Object to encode
514: * @return An object (of type byte[]) containing the
515: * base64 encoded data which corresponds to the byte[] supplied.
516: * @throws IOException if the parameter supplied is not
517: * of type byte[]
518: */
519: public Object encode(Object pObject) throws IOException {
520: if (!(pObject instanceof byte[])) {
521: throw new IOException(
522: "Parameter supplied to Base64 encode is not a byte[]");
523: }
524: return encode((byte[]) pObject);
525: }
526:
527: /**
528: * Encodes a byte[] containing binary data, into a byte[] containing
529: * characters in the Base64 alphabet.
530: *
531: * @param pArray a byte array containing binary data
532: * @return A byte array containing only Base64 character data
533: */
534: public byte[] encode(byte[] pArray) {
535: return encodeBase64(pArray, false);
536: }
537:
538: }
|