001: /*
002: * ====================================================================
003: *
004: * The Apache Software License, Version 1.1
005: *
006: * Copyright (c) 1999-2003 The Apache Software Foundation. All rights
007: * reserved.
008: *
009: * Redistribution and use in source and binary forms, with or without
010: * modification, are permitted provided that the following conditions
011: * are met:
012: *
013: * 1. Redistributions of source code must retain the above copyright
014: * notice, this list of conditions and the following disclaimer.
015: *
016: * 2. Redistributions in binary form must reproduce the above copyright
017: * notice, this list of conditions and the following disclaimer in
018: * the documentation and/or other materials provided with the
019: * distribution.
020: *
021: * 3. The end-user documentation included with the redistribution, if
022: * any, must include the following acknowlegement:
023: * "This product includes software developed by the
024: * Apache Software Foundation (http://www.apache.org/)."
025: * Alternately, this acknowlegement may appear in the software itself,
026: * if and wherever such third-party acknowlegements normally appear.
027: *
028: * 4. The names "The Jakarta Project", "Commons", and "Apache Software
029: * Foundation" must not be used to endorse or promote products derived
030: * from this software without prior written permission. For written
031: * permission, please contact apache@apache.org.
032: *
033: * 5. Products derived from this software may not be called "Apache"
034: * nor may "Apache" appear in their names without prior written
035: * permission of the Apache Group.
036: *
037: * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
038: * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
039: * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
040: * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
041: * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
042: * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
043: * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
044: * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
045: * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
046: * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
047: * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
048: * SUCH DAMAGE.
049: * ====================================================================
050: *
051: * This software consists of voluntary contributions made by many
052: * individuals on behalf of the Apache Software Foundation. For more
053: * information on the Apache Software Foundation, please see
054: * <http://www.apache.org/>.
055: */
056:
057: package org.jicarilla.http.util;
058:
059: import org.jicarilla.http.HTTPEncoding;
060: import org.jicarilla.lang.CascadingRuntimeException;
061:
062: import java.io.UnsupportedEncodingException;
063:
064: /**
065: * Base64 encoder and decoder.
066: * <p>
067: * This class provides encoding/decoding methods for the Base64 encoding as
068: * defined by RFC 2045, N. Freed and N. Borenstein. RFC 2045: Multipurpose
069: * Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies.
070: * Reference 1996. Available at:
071: * <a href="http://www.ietf.org/rfc/rfc2045.txt">http://www.ietf.org/rfc/rfc2045.txt</a>
072: * </p>
073: *
074: * This class is originally from the
075: * <a href="http://jakarta.apache.org/">Jakarta Commons</a> httpclient
076: * libraries.
077: *
078: * @author <a href="mailto: lsimons at jicarilla dot org">Leo Simons</a>
079: * @author Jeffrey Rodriguez
080: * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
081: * @version $Id: Base64.java,v 1.5 2004/03/23 13:37:48 lsimons Exp $
082: *
083: */
084: public final class Base64 {
085: /** disable instantiation */
086: private Base64() {
087: }
088:
089: protected static final int BASELENGTH = 255;
090: protected static final int LOOKUPLENGTH = 64;
091: protected static final int TWENTYFOURBITGROUP = 24;
092: protected static final int EIGHTBIT = 8;
093: protected static final int SIXTEENBIT = 16;
094: // unused protected static final int SIXBIT = 6;
095: protected static final int FOURBYTE = 4;
096: protected static final int SIGN = -128;
097: protected static final byte PAD = (byte) '=';
098: protected static final byte[] BASE64_ALPHABET = new byte[BASELENGTH];
099: protected static final byte[] LOOKUP_BASE64_ALPHABET = new byte[LOOKUPLENGTH];
100:
101: static {
102: for (int i = 0; i < BASELENGTH; i++) {
103: BASE64_ALPHABET[i] = -1;
104: }
105: for (int i = 'Z'; i >= 'A'; i--) {
106: BASE64_ALPHABET[i] = (byte) (i - 'A');
107: }
108: for (int i = 'z'; i >= 'a'; i--) {
109: BASE64_ALPHABET[i] = (byte) (i - 'a' + 26);
110: }
111: for (int i = '9'; i >= '0'; i--) {
112: BASE64_ALPHABET[i] = (byte) (i - '0' + 52);
113: }
114:
115: BASE64_ALPHABET['+'] = 62;
116: BASE64_ALPHABET['/'] = 63;
117:
118: for (int i = 0; i <= 25; i++) {
119: LOOKUP_BASE64_ALPHABET[i] = (byte) ('A' + i);
120: }
121:
122: for (int i = 26, j = 0; i <= 51; i++, j++) {
123: LOOKUP_BASE64_ALPHABET[i] = (byte) ('a' + j);
124: }
125:
126: for (int i = 52, j = 0; i <= 61; i++, j++) {
127: LOOKUP_BASE64_ALPHABET[i] = (byte) ('0' + j);
128: }
129: LOOKUP_BASE64_ALPHABET[62] = (byte) '+';
130: LOOKUP_BASE64_ALPHABET[63] = (byte) '/';
131: }
132:
133: /**
134: * Return true if the specified string is base64 encoded.
135: *
136: * @param isValidString The string to test.
137: * @return boolean True if the string is base64.
138: */
139: public static boolean isBase64(final String isValidString) {
140: return isArrayByteBase64(getAsciiBytes(isValidString));
141: }
142:
143: /**
144: * Return true if the specified octect is base64.
145: *
146: * @param octect The octet to test.
147: * @return boolean True if the octect is base64.
148: */
149: static boolean isBase64(final byte octect) {
150: return (octect == PAD || BASE64_ALPHABET[octect] != -1);
151: }
152:
153: /**
154: * Return true if the specified byte array is base64.
155: *
156: * @param arrayOctect The array to test.
157: * @return boolean true if the specified byte array is base64
158: */
159: public static boolean isArrayByteBase64(final byte[] arrayOctect) {
160: final int length = arrayOctect.length;
161: if (length == 0)
162: return true;
163:
164: for (int i = 0; i < length; i++) {
165: if (!Base64.isBase64(arrayOctect[i]))
166: return false;
167: }
168: return true;
169: }
170:
171: /**
172: * Encodes hex octects into Base64
173: *
174: * @param binaryData Array containing binaryData
175: * @return Base64-encoded array
176: */
177: public static byte[] encode(final byte[] binaryData) {
178:
179: final int lengthDataBits = binaryData.length * EIGHTBIT;
180: final int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;
181: final int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;
182: byte[] encodedData = null;
183:
184: if (fewerThan24bits != 0)
185: //data not divisible by 24 bit
186: encodedData = new byte[(numberTriplets + 1) * 4];
187: else
188: // 16 or 8 bit
189: encodedData = new byte[numberTriplets * 4];
190:
191: byte k = 0;
192: byte l = 0;
193: byte b1 = 0;
194: byte b2 = 0;
195: byte b3 = 0;
196:
197: int encodedIndex = 0;
198: int dataIndex = 0;
199: int i = 0;
200:
201: for (i = 0; i < numberTriplets; i++) {
202: dataIndex = i * 3;
203: b1 = binaryData[dataIndex];
204: b2 = binaryData[dataIndex + 1];
205: b3 = binaryData[dataIndex + 2];
206:
207: l = (byte) (b2 & 0x0f);
208: k = (byte) (b1 & 0x03);
209:
210: encodedIndex = i * 4;
211: final byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2)
212: : (byte) ((b1) >> 2 ^ 0xc0);
213:
214: final byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4)
215: : (byte) ((b2) >> 4 ^ 0xf0);
216: final byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6)
217: : (byte) ((b3) >> 6 ^ 0xfc);
218:
219: encodedData[encodedIndex] = LOOKUP_BASE64_ALPHABET[val1];
220: encodedData[encodedIndex + 1] = LOOKUP_BASE64_ALPHABET[val2
221: | (k << 4)];
222: encodedData[encodedIndex + 2] = LOOKUP_BASE64_ALPHABET[(l << 2)
223: | val3];
224: encodedData[encodedIndex + 3] = LOOKUP_BASE64_ALPHABET[b3 & 0x3f];
225: }
226:
227: // form integral number of 6-bit groups
228: dataIndex = i * 3;
229: encodedIndex = i * 4;
230: if (fewerThan24bits == EIGHTBIT) {
231: b1 = binaryData[dataIndex];
232: k = (byte) (b1 & 0x03);
233: final byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2)
234: : (byte) ((b1) >> 2 ^ 0xc0);
235: encodedData[encodedIndex] = LOOKUP_BASE64_ALPHABET[val1];
236: encodedData[encodedIndex + 1] = LOOKUP_BASE64_ALPHABET[k << 4];
237: encodedData[encodedIndex + 2] = PAD;
238: encodedData[encodedIndex + 3] = PAD;
239: } else if (fewerThan24bits == SIXTEENBIT) {
240: b1 = binaryData[dataIndex];
241: b2 = binaryData[dataIndex + 1];
242: l = (byte) (b2 & 0x0f);
243: k = (byte) (b1 & 0x03);
244:
245: final byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2)
246: : (byte) ((b1) >> 2 ^ 0xc0);
247: final byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4)
248: : (byte) ((b2) >> 4 ^ 0xf0);
249:
250: encodedData[encodedIndex] = LOOKUP_BASE64_ALPHABET[val1];
251: encodedData[encodedIndex + 1] = LOOKUP_BASE64_ALPHABET[val2
252: | (k << 4)];
253: encodedData[encodedIndex + 2] = LOOKUP_BASE64_ALPHABET[l << 2];
254: encodedData[encodedIndex + 3] = PAD;
255: }
256: return encodedData;
257: }
258:
259: /**
260: * Decodes Base64 data into octects
261: *
262: * @param base64Data byte array containing Base64 data
263: * @return Array containing decoded data.
264: */
265: public static byte[] decode(final byte[] base64Data) {
266: // Should we throw away anything not in base64Data ?
267:
268: // handle the edge case, so we don't have to worry about it later
269: if (base64Data.length == 0)
270: return new byte[0];
271:
272: final int numberQuadruple = base64Data.length / FOURBYTE;
273: byte[] decodedData = null;
274: byte b1 = 0, b2 = 0, b3 = 0, b4 = 0, marker0 = 0, marker1 = 0;
275:
276: int encodedIndex = 0;
277: int dataIndex = 0;
278: {
279: // this block sizes the output array properly - rlw
280: int lastData = base64Data.length;
281: // ignore the '=' padding
282: while (base64Data[lastData - 1] == PAD) {
283: if (--lastData == 0) {
284: return new byte[0];
285: }
286: }
287: decodedData = new byte[lastData - numberQuadruple];
288: }
289:
290: for (int i = 0; i < numberQuadruple; i++) {
291: dataIndex = i * 4;
292: marker0 = base64Data[dataIndex + 2];
293: marker1 = base64Data[dataIndex + 3];
294:
295: b1 = BASE64_ALPHABET[base64Data[dataIndex]];
296: b2 = BASE64_ALPHABET[base64Data[dataIndex + 1]];
297:
298: if (marker0 != PAD && marker1 != PAD) { //No PAD e.g 3cQl
299: b3 = BASE64_ALPHABET[marker0];
300: b4 = BASE64_ALPHABET[marker1];
301:
302: decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
303: decodedData[encodedIndex + 1] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
304: decodedData[encodedIndex + 2] = (byte) (b3 << 6 | b4);
305: } else if (marker0 == PAD) { //Two PAD e.g. 3c[Pad][Pad]
306: decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
307: } else if (marker1 == PAD) { //One PAD e.g. 3cQ[Pad]
308: b3 = BASE64_ALPHABET[marker0];
309: decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
310: decodedData[encodedIndex + 1] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
311: }
312: encodedIndex += 3;
313: }
314: return decodedData;
315: }
316:
317: /**
318: * Converts the specified string to byte array of ASCII characters.
319: *
320: * @param data the string to be encoded
321: * @return The string as a byte array.
322: * @throws java.lang.RuntimeException if there is a problem converting to bytes
323: * using US-ASCII
324: */
325: public static byte[] getAsciiBytes(final String data) {
326: if (data == null)
327: throw new IllegalArgumentException(
328: "Parameter may not be null");
329:
330: try {
331: return data.getBytes(HTTPEncoding.USASCII_CHARSET);
332: } catch (UnsupportedEncodingException uee) {
333: throw new CascadingRuntimeException(
334: "The underlying JVM does not properly support US-ASCII!",
335: uee);
336: }
337: }
338: }
|