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