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