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: */
017: package org.apache.wicket.util.crypt;
018:
019: /**
020: * Provides Base64 encoding and decoding as defined by RFC 2045.
021: * <p/>
022: * This class is taken from the Apache commons-codec, and adjusted to fit the
023: * Wicket framework's needs, especially external dependencies have been removed.
024: * </p>
025: * <p/>
026: * This class implements section <cite>6.8. Base64 Content-Transfer-Encoding</cite>
027: * from RFC 2045 <cite>Multipurpose Internet Mail Extensions (MIME) Part One:
028: * Format of Internet Message Bodies</cite> by Freed and Borenstein.</p>
029: *
030: * @author Apache Software Foundation
031: * @since 1.2
032: */
033: public class Base64 {
034: /**
035: * Chunk size per RFC 2045 section 6.8.
036: * <p/>
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: arrayOctect = discardWhitespace(arrayOctect);
178:
179: int length = arrayOctect.length;
180: if (length == 0) {
181: // shouldn't a 0 length array be valid base64 data?
182: // return false;
183: return true;
184: }
185: for (int i = 0; i < length; i++) {
186: if (!isBase64(arrayOctect[i])) {
187: return false;
188: }
189: }
190: return true;
191: }
192:
193: /**
194: * Encodes binary data using the base64 algorithm but
195: * does not chunk the output.
196: *
197: * @param binaryData binary data to encode
198: * @return Base64 characters
199: */
200: public static byte[] encodeBase64(byte[] binaryData) {
201: return encodeBase64(binaryData, false);
202: }
203:
204: /**
205: * Encodes binary data using the base64 algorithm and chunks
206: * the encoded output into 76 character blocks
207: *
208: * @param binaryData binary data to encode
209: * @return Base64 characters chunked in 76 character blocks
210: */
211: public static byte[] encodeBase64Chunked(byte[] binaryData) {
212: return encodeBase64(binaryData, true);
213: }
214:
215: /**
216: * Decodes an Object using the base64 algorithm. This method
217: * is provided in order to satisfy the requirements of the
218: * Decoder interface, and will throw a DecoderException if the
219: * supplied object is not of type byte[].
220: *
221: * @param pObject Object to decode
222: * @return An object (of type byte[]) containing the
223: * binary data which corresponds to the byte[] supplied.
224: * @throws IllegalArgumentException if the parameter supplied is not
225: * of type byte[]
226: */
227: public Object decode(Object pObject) {
228: if (!(pObject instanceof byte[])) {
229: throw new IllegalArgumentException(
230: "Parameter supplied to Base64 decode is not a byte[]");
231: }
232: return decode((byte[]) pObject);
233: }
234:
235: /**
236: * Decodes a byte[] containing containing
237: * characters in the Base64 alphabet.
238: *
239: * @param pArray A byte array containing Base64 character data
240: * @return a byte array containing binary data
241: */
242: public byte[] decode(byte[] pArray) {
243: return decodeBase64(pArray);
244: }
245:
246: /**
247: * Encodes binary data using the base64 algorithm, optionally
248: * chunking the output into 76 character blocks.
249: *
250: * @param binaryData Array containing binary data to encode.
251: * @param isChunked if <code>true</code> this encoder will chunk
252: * the base64 output into 76 character blocks
253: * @return Base64-encoded data.
254: */
255: public static byte[] encodeBase64(byte[] binaryData,
256: boolean isChunked) {
257: int lengthDataBits = binaryData.length * EIGHTBIT;
258: int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;
259: int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;
260: byte encodedData[] = null;
261: int encodedDataLength = 0;
262: int nbrChunks = 0;
263:
264: if (fewerThan24bits != 0) {
265: //data not divisible by 24 bit
266: encodedDataLength = (numberTriplets + 1) * 4;
267: } else {
268: // 16 or 8 bit
269: encodedDataLength = numberTriplets * 4;
270: }
271:
272: // If the output is to be "chunked" into 76 character sections,
273: // for compliance with RFC 2045 MIME, then it is important to
274: // allow for extra length to account for the separator(s)
275: if (isChunked) {
276:
277: nbrChunks = (CHUNK_SEPARATOR.length == 0 ? 0 : (int) Math
278: .ceil((float) encodedDataLength / CHUNK_SIZE));
279: encodedDataLength += nbrChunks * CHUNK_SEPARATOR.length;
280: }
281:
282: encodedData = new byte[encodedDataLength];
283:
284: byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;
285:
286: int encodedIndex = 0;
287: int dataIndex = 0;
288: int i = 0;
289: int nextSeparatorIndex = CHUNK_SIZE;
290: int chunksSoFar = 0;
291:
292: //log.debug("number of triplets = " + numberTriplets);
293: for (i = 0; i < numberTriplets; i++) {
294: dataIndex = i * 3;
295: b1 = binaryData[dataIndex];
296: b2 = binaryData[dataIndex + 1];
297: b3 = binaryData[dataIndex + 2];
298:
299: //log.debug("b1= " + b1 +", b2= " + b2 + ", b3= " + b3);
300:
301: l = (byte) (b2 & 0x0f);
302: k = (byte) (b1 & 0x03);
303:
304: byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2)
305: : (byte) ((b1) >> 2 ^ 0xc0);
306: byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4)
307: : (byte) ((b2) >> 4 ^ 0xf0);
308: byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6)
309: : (byte) ((b3) >> 6 ^ 0xfc);
310:
311: encodedData[encodedIndex] = lookUpBase64Alphabet[val1];
312: //log.debug( "val2 = " + val2 );
313: //log.debug( "k4 = " + (k<<4) );
314: //log.debug( "vak = " + (val2 | (k<<4)) );
315: encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2
316: | (k << 4)];
317: encodedData[encodedIndex + 2] = lookUpBase64Alphabet[(l << 2)
318: | val3];
319: encodedData[encodedIndex + 3] = lookUpBase64Alphabet[b3 & 0x3f];
320:
321: encodedIndex += 4;
322:
323: // If we are chunking, let's put a chunk separator down.
324: if (isChunked) {
325: // this assumes that CHUNK_SIZE % 4 == 0
326: if (encodedIndex == nextSeparatorIndex) {
327: System.arraycopy(CHUNK_SEPARATOR, 0, encodedData,
328: encodedIndex, CHUNK_SEPARATOR.length);
329: chunksSoFar++;
330: nextSeparatorIndex = (CHUNK_SIZE * (chunksSoFar + 1))
331: + (chunksSoFar * CHUNK_SEPARATOR.length);
332: encodedIndex += CHUNK_SEPARATOR.length;
333: }
334: }
335: }
336:
337: // form integral number of 6-bit groups
338: dataIndex = i * 3;
339:
340: if (fewerThan24bits == EIGHTBIT) {
341: b1 = binaryData[dataIndex];
342: k = (byte) (b1 & 0x03);
343: //log.debug("b1=" + b1);
344: //log.debug("b1<<2 = " + (b1>>2) );
345: byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2)
346: : (byte) ((b1) >> 2 ^ 0xc0);
347: encodedData[encodedIndex] = lookUpBase64Alphabet[val1];
348: encodedData[encodedIndex + 1] = lookUpBase64Alphabet[k << 4];
349: encodedData[encodedIndex + 2] = PAD;
350: encodedData[encodedIndex + 3] = PAD;
351: } else if (fewerThan24bits == SIXTEENBIT) {
352:
353: b1 = binaryData[dataIndex];
354: b2 = binaryData[dataIndex + 1];
355: l = (byte) (b2 & 0x0f);
356: k = (byte) (b1 & 0x03);
357:
358: byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2)
359: : (byte) ((b1) >> 2 ^ 0xc0);
360: byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4)
361: : (byte) ((b2) >> 4 ^ 0xf0);
362:
363: encodedData[encodedIndex] = lookUpBase64Alphabet[val1];
364: encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2
365: | (k << 4)];
366: encodedData[encodedIndex + 2] = lookUpBase64Alphabet[l << 2];
367: encodedData[encodedIndex + 3] = PAD;
368: }
369:
370: if (isChunked) {
371: // we also add a separator to the end of the final chunk.
372: if (chunksSoFar < nbrChunks) {
373: System.arraycopy(CHUNK_SEPARATOR, 0, encodedData,
374: encodedDataLength - CHUNK_SEPARATOR.length,
375: CHUNK_SEPARATOR.length);
376: }
377: }
378:
379: return encodedData;
380: }
381:
382: /**
383: * Decodes Base64 data into octects
384: *
385: * @param base64Data Byte array containing Base64 data
386: * @return Array containing decoded data.
387: */
388: public static byte[] decodeBase64(byte[] base64Data) {
389: // RFC 2045 requires that we discard ALL non-Base64 characters
390: base64Data = discardNonBase64(base64Data);
391:
392: // handle the edge case, so we don't have to worry about it later
393: if (base64Data.length == 0) {
394: return new byte[0];
395: }
396:
397: int numberQuadruple = base64Data.length / FOURBYTE;
398: byte decodedData[] = null;
399: byte b1 = 0, b2 = 0, b3 = 0, b4 = 0, marker0 = 0, marker1 = 0;
400:
401: // Throw away anything not in base64Data
402:
403: int encodedIndex = 0;
404: int dataIndex = 0;
405: {
406: // this sizes the output array properly - rlw
407: int lastData = base64Data.length;
408: // ignore the '=' padding
409: while (base64Data[lastData - 1] == PAD) {
410: if (--lastData == 0) {
411: return new byte[0];
412: }
413: }
414: decodedData = new byte[lastData - numberQuadruple];
415: }
416:
417: for (int i = 0; i < numberQuadruple; i++) {
418: dataIndex = i * 4;
419: marker0 = base64Data[dataIndex + 2];
420: marker1 = base64Data[dataIndex + 3];
421:
422: b1 = base64Alphabet[base64Data[dataIndex]];
423: b2 = base64Alphabet[base64Data[dataIndex + 1]];
424:
425: if (marker0 != PAD && marker1 != PAD) {
426: //No PAD e.g 3cQl
427: b3 = base64Alphabet[marker0];
428: b4 = base64Alphabet[marker1];
429:
430: decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
431: decodedData[encodedIndex + 1] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
432: decodedData[encodedIndex + 2] = (byte) (b3 << 6 | b4);
433: } else if (marker0 == PAD) {
434: //Two PAD e.g. 3c[Pad][Pad]
435: decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
436: } else if (marker1 == PAD) {
437: //One PAD e.g. 3cQ[Pad]
438: b3 = base64Alphabet[marker0];
439:
440: decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
441: decodedData[encodedIndex + 1] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
442: }
443: encodedIndex += 3;
444: }
445: return decodedData;
446: }
447:
448: /**
449: * Discards any whitespace from a base-64 encoded block.
450: *
451: * @param data The base-64 encoded data to discard the whitespace
452: * from.
453: * @return The data, less whitespace (see RFC 2045).
454: */
455: static byte[] discardWhitespace(byte[] data) {
456: byte groomedData[] = new byte[data.length];
457: int bytesCopied = 0;
458:
459: for (int i = 0; i < data.length; i++) {
460: switch (data[i]) {
461: case (byte) ' ':
462: case (byte) '\n':
463: case (byte) '\r':
464: case (byte) '\t':
465: break;
466: default:
467: groomedData[bytesCopied++] = data[i];
468: }
469: }
470:
471: byte packedData[] = new byte[bytesCopied];
472:
473: System.arraycopy(groomedData, 0, packedData, 0, bytesCopied);
474:
475: return packedData;
476: }
477:
478: /**
479: * Discards any characters outside of the base64 alphabet, per
480: * the requirements on page 25 of RFC 2045 - "Any characters
481: * outside of the base64 alphabet are to be ignored in base64
482: * encoded data."
483: *
484: * @param data The base-64 encoded data to groom
485: * @return The data, less non-base64 characters (see RFC 2045).
486: */
487: static byte[] discardNonBase64(byte[] data) {
488: byte groomedData[] = new byte[data.length];
489: int bytesCopied = 0;
490:
491: for (int i = 0; i < data.length; i++) {
492: if (isBase64(data[i])) {
493: groomedData[bytesCopied++] = data[i];
494: }
495: }
496:
497: byte packedData[] = new byte[bytesCopied];
498:
499: System.arraycopy(groomedData, 0, packedData, 0, bytesCopied);
500:
501: return packedData;
502: }
503:
504: // Implementation of the Encoder Interface
505:
506: /**
507: * Encodes an Object using the base64 algorithm. This method
508: * is provided in order to satisfy the requirements of the
509: * Encoder interface, and will throw an EncoderException if the
510: * supplied object is not of type byte[].
511: *
512: * @param pObject Object to encode
513: * @return An object (of type byte[]) containing the
514: * base64 encoded data which corresponds to the byte[] supplied.
515: * @throws IllegalArgumentException if the parameter supplied is not
516: * of type byte[]
517: */
518: public Object encode(Object pObject) {
519: if (!(pObject instanceof byte[])) {
520: throw new IllegalArgumentException(
521: "Parameter supplied to Base64 encode is not a byte[]");
522: }
523: return encode((byte[]) pObject);
524: }
525:
526: /**
527: * Encodes a byte[] containing binary data, into a byte[] containing
528: * characters in the Base64 alphabet.
529: *
530: * @param pArray a byte array containing binary data
531: * @return A byte array containing only Base64 character data
532: */
533: public byte[] encode(byte[] pArray) {
534: return encodeBase64(pArray, false);
535: }
536:
537: }
|