--- /dev/null
+/*\r
+ * Copyright 2001-2004 The Apache Software Foundation.\r
+ * \r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ */ \r
+\r
+package org.apache.commons.codec.binary;\r
+\r
+import org.apache.commons.codec.BinaryDecoder;\r
+import org.apache.commons.codec.BinaryEncoder;\r
+import org.apache.commons.codec.DecoderException;\r
+import org.apache.commons.codec.EncoderException;\r
+\r
+/**\r
+ * Provides Base64 encoding and decoding as defined by RFC 2045.\r
+ * \r
+ * <p>This class implements section <cite>6.8. Base64 Content-Transfer-Encoding</cite> \r
+ * from RFC 2045 <cite>Multipurpose Internet Mail Extensions (MIME) Part One: \r
+ * Format of Internet Message Bodies</cite> by Freed and Borenstein.</p> \r
+ *\r
+ * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>\r
+ * @author Apache Software Foundation\r
+ * @since 1.0-dev\r
+ * @version $Id$\r
+ */\r
+public class Base64 implements BinaryEncoder, BinaryDecoder {\r
+\r
+ /**\r
+ * Chunk size per RFC 2045 section 6.8.\r
+ * \r
+ * <p>The {@value} character limit does not count the trailing CRLF, but counts \r
+ * all other characters, including any equal signs.</p>\r
+ * \r
+ * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 6.8</a>\r
+ */\r
+ static final int CHUNK_SIZE = 76;\r
+\r
+ /**\r
+ * Chunk separator per RFC 2045 section 2.1.\r
+ * \r
+ * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 2.1</a>\r
+ */\r
+ static final byte[] CHUNK_SEPARATOR = "\r\n".getBytes();\r
+\r
+ /**\r
+ * The base length.\r
+ */\r
+ static final int BASELENGTH = 255;\r
+\r
+ /**\r
+ * Lookup length.\r
+ */\r
+ static final int LOOKUPLENGTH = 64;\r
+\r
+ /**\r
+ * Used to calculate the number of bits in a byte.\r
+ */\r
+ static final int EIGHTBIT = 8;\r
+\r
+ /**\r
+ * Used when encoding something which has fewer than 24 bits.\r
+ */\r
+ static final int SIXTEENBIT = 16;\r
+\r
+ /**\r
+ * Used to determine how many bits data contains.\r
+ */\r
+ static final int TWENTYFOURBITGROUP = 24;\r
+\r
+ /**\r
+ * Used to get the number of Quadruples.\r
+ */\r
+ static final int FOURBYTE = 4;\r
+\r
+ /**\r
+ * Used to test the sign of a byte.\r
+ */\r
+ static final int SIGN = -128;\r
+ \r
+ /**\r
+ * Byte used to pad output.\r
+ */\r
+ static final byte PAD = (byte) '=';\r
+\r
+ // Create arrays to hold the base64 characters and a \r
+ // lookup for base64 chars\r
+ private static byte[] base64Alphabet = new byte[BASELENGTH];\r
+ private static byte[] lookUpBase64Alphabet = new byte[LOOKUPLENGTH];\r
+\r
+ // Populating the lookup and character arrays\r
+ static {\r
+ for (int i = 0; i < BASELENGTH; i++) {\r
+ base64Alphabet[i] = (byte) -1;\r
+ }\r
+ for (int i = 'Z'; i >= 'A'; i--) {\r
+ base64Alphabet[i] = (byte) (i - 'A');\r
+ }\r
+ for (int i = 'z'; i >= 'a'; i--) {\r
+ base64Alphabet[i] = (byte) (i - 'a' + 26);\r
+ }\r
+ for (int i = '9'; i >= '0'; i--) {\r
+ base64Alphabet[i] = (byte) (i - '0' + 52);\r
+ }\r
+\r
+ base64Alphabet['+'] = 62;\r
+ base64Alphabet['/'] = 63;\r
+\r
+ for (int i = 0; i <= 25; i++) {\r
+ lookUpBase64Alphabet[i] = (byte) ('A' + i);\r
+ }\r
+\r
+ for (int i = 26, j = 0; i <= 51; i++, j++) {\r
+ lookUpBase64Alphabet[i] = (byte) ('a' + j);\r
+ }\r
+\r
+ for (int i = 52, j = 0; i <= 61; i++, j++) {\r
+ lookUpBase64Alphabet[i] = (byte) ('0' + j);\r
+ }\r
+\r
+ lookUpBase64Alphabet[62] = (byte) '+';\r
+ lookUpBase64Alphabet[63] = (byte) '/';\r
+ }\r
+\r
+ private static boolean isBase64(byte octect) {\r
+ if (octect == PAD) {\r
+ return true;\r
+ } else if (base64Alphabet[octect] == -1) {\r
+ return false;\r
+ } else {\r
+ return true;\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Tests a given byte array to see if it contains\r
+ * only valid characters within the Base64 alphabet.\r
+ *\r
+ * @param arrayOctect byte array to test\r
+ * @return true if all bytes are valid characters in the Base64\r
+ * alphabet or if the byte array is empty; false, otherwise\r
+ */\r
+ public static boolean isArrayByteBase64(byte[] arrayOctect) {\r
+\r
+ arrayOctect = discardWhitespace(arrayOctect);\r
+\r
+ int length = arrayOctect.length;\r
+ if (length == 0) {\r
+ // shouldn't a 0 length array be valid base64 data?\r
+ // return false;\r
+ return true;\r
+ }\r
+ for (int i = 0; i < length; i++) {\r
+ if (!isBase64(arrayOctect[i])) {\r
+ return false;\r
+ }\r
+ }\r
+ return true;\r
+ }\r
+\r
+ /**\r
+ * Encodes binary data using the base64 algorithm but\r
+ * does not chunk the output.\r
+ *\r
+ * @param binaryData binary data to encode\r
+ * @return Base64 characters\r
+ */\r
+ public static byte[] encodeBase64(byte[] binaryData) {\r
+ return encodeBase64(binaryData, false);\r
+ }\r
+\r
+ /**\r
+ * Encodes binary data using the base64 algorithm and chunks\r
+ * the encoded output into 76 character blocks\r
+ *\r
+ * @param binaryData binary data to encode\r
+ * @return Base64 characters chunked in 76 character blocks\r
+ */\r
+ public static byte[] encodeBase64Chunked(byte[] binaryData) {\r
+ return encodeBase64(binaryData, true);\r
+ }\r
+\r
+\r
+ /**\r
+ * Decodes an Object using the base64 algorithm. This method\r
+ * is provided in order to satisfy the requirements of the\r
+ * Decoder interface, and will throw a DecoderException if the\r
+ * supplied object is not of type byte[].\r
+ *\r
+ * @param pObject Object to decode\r
+ * @return An object (of type byte[]) containing the \r
+ * binary data which corresponds to the byte[] supplied.\r
+ * @throws DecoderException if the parameter supplied is not\r
+ * of type byte[]\r
+ */\r
+ public Object decode(Object pObject) throws DecoderException {\r
+ if (!(pObject instanceof byte[])) {\r
+ throw new DecoderException("Parameter supplied to Base64 decode is not a byte[]");\r
+ }\r
+ return decode((byte[]) pObject);\r
+ }\r
+\r
+ /**\r
+ * Decodes a byte[] containing containing\r
+ * characters in the Base64 alphabet.\r
+ *\r
+ * @param pArray A byte array containing Base64 character data\r
+ * @return a byte array containing binary data\r
+ */\r
+ public byte[] decode(byte[] pArray) {\r
+ return decodeBase64(pArray);\r
+ }\r
+\r
+ /**\r
+ * Encodes binary data using the base64 algorithm, optionally\r
+ * chunking the output into 76 character blocks.\r
+ *\r
+ * @param binaryData Array containing binary data to encode.\r
+ * @param isChunked if isChunked is true this encoder will chunk\r
+ * the base64 output into 76 character blocks\r
+ * @return Base64-encoded data.\r
+ */\r
+ public static byte[] encodeBase64(byte[] binaryData, boolean isChunked) {\r
+ int lengthDataBits = binaryData.length * EIGHTBIT;\r
+ int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;\r
+ int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;\r
+ byte encodedData[] = null;\r
+ int encodedDataLength = 0;\r
+ int nbrChunks = 0;\r
+\r
+ if (fewerThan24bits != 0) {\r
+ //data not divisible by 24 bit\r
+ encodedDataLength = (numberTriplets + 1) * 4;\r
+ } else {\r
+ // 16 or 8 bit\r
+ encodedDataLength = numberTriplets * 4;\r
+ }\r
+\r
+ // If the output is to be "chunked" into 76 character sections, \r
+ // for compliance with RFC 2045 MIME, then it is important to \r
+ // allow for extra length to account for the separator(s)\r
+ if (isChunked) {\r
+\r
+ nbrChunks =\r
+ (CHUNK_SEPARATOR.length == 0 ? 0 : (int) Math.ceil((float) encodedDataLength / CHUNK_SIZE));\r
+ encodedDataLength += nbrChunks * CHUNK_SEPARATOR.length;\r
+ }\r
+\r
+ encodedData = new byte[encodedDataLength];\r
+\r
+ byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;\r
+\r
+ int encodedIndex = 0;\r
+ int dataIndex = 0;\r
+ int i = 0;\r
+ int nextSeparatorIndex = CHUNK_SIZE;\r
+ int chunksSoFar = 0;\r
+\r
+ //log.debug("number of triplets = " + numberTriplets);\r
+ for (i = 0; i < numberTriplets; i++) {\r
+ dataIndex = i * 3;\r
+ b1 = binaryData[dataIndex];\r
+ b2 = binaryData[dataIndex + 1];\r
+ b3 = binaryData[dataIndex + 2];\r
+\r
+ //log.debug("b1= " + b1 +", b2= " + b2 + ", b3= " + b3);\r
+\r
+ l = (byte) (b2 & 0x0f);\r
+ k = (byte) (b1 & 0x03);\r
+\r
+ byte val1 =\r
+ ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);\r
+ byte val2 =\r
+ ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);\r
+ byte val3 =\r
+ ((b3 & SIGN) == 0) ? (byte) (b3 >> 6) : (byte) ((b3) >> 6 ^ 0xfc);\r
+\r
+ encodedData[encodedIndex] = lookUpBase64Alphabet[val1];\r
+ //log.debug( "val2 = " + val2 );\r
+ //log.debug( "k4 = " + (k<<4) );\r
+ //log.debug( "vak = " + (val2 | (k<<4)) );\r
+ encodedData[encodedIndex + 1] =\r
+ lookUpBase64Alphabet[val2 | (k << 4)];\r
+ encodedData[encodedIndex + 2] =\r
+ lookUpBase64Alphabet[(l << 2) | val3];\r
+ encodedData[encodedIndex + 3] = lookUpBase64Alphabet[b3 & 0x3f];\r
+\r
+ encodedIndex += 4;\r
+\r
+ // If we are chunking, let's put a chunk separator down.\r
+ if (isChunked) {\r
+ // this assumes that CHUNK_SIZE % 4 == 0\r
+ if (encodedIndex == nextSeparatorIndex) {\r
+ System.arraycopy(\r
+ CHUNK_SEPARATOR,\r
+ 0,\r
+ encodedData,\r
+ encodedIndex,\r
+ CHUNK_SEPARATOR.length);\r
+ chunksSoFar++;\r
+ nextSeparatorIndex =\r
+ (CHUNK_SIZE * (chunksSoFar + 1)) + \r
+ (chunksSoFar * CHUNK_SEPARATOR.length);\r
+ encodedIndex += CHUNK_SEPARATOR.length;\r
+ }\r
+ }\r
+ }\r
+\r
+ // form integral number of 6-bit groups\r
+ dataIndex = i * 3;\r
+\r
+ if (fewerThan24bits == EIGHTBIT) {\r
+ b1 = binaryData[dataIndex];\r
+ k = (byte) (b1 & 0x03);\r
+ //log.debug("b1=" + b1);\r
+ //log.debug("b1<<2 = " + (b1>>2) );\r
+ byte val1 =\r
+ ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);\r
+ encodedData[encodedIndex] = lookUpBase64Alphabet[val1];\r
+ encodedData[encodedIndex + 1] = lookUpBase64Alphabet[k << 4];\r
+ encodedData[encodedIndex + 2] = PAD;\r
+ encodedData[encodedIndex + 3] = PAD;\r
+ } else if (fewerThan24bits == SIXTEENBIT) {\r
+\r
+ b1 = binaryData[dataIndex];\r
+ b2 = binaryData[dataIndex + 1];\r
+ l = (byte) (b2 & 0x0f);\r
+ k = (byte) (b1 & 0x03);\r
+\r
+ byte val1 =\r
+ ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);\r
+ byte val2 =\r
+ ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);\r
+\r
+ encodedData[encodedIndex] = lookUpBase64Alphabet[val1];\r
+ encodedData[encodedIndex + 1] =\r
+ lookUpBase64Alphabet[val2 | (k << 4)];\r
+ encodedData[encodedIndex + 2] = lookUpBase64Alphabet[l << 2];\r
+ encodedData[encodedIndex + 3] = PAD;\r
+ }\r
+\r
+ if (isChunked) {\r
+ // we also add a separator to the end of the final chunk.\r
+ if (chunksSoFar < nbrChunks) {\r
+ System.arraycopy(\r
+ CHUNK_SEPARATOR,\r
+ 0,\r
+ encodedData,\r
+ encodedDataLength - CHUNK_SEPARATOR.length,\r
+ CHUNK_SEPARATOR.length);\r
+ }\r
+ }\r
+\r
+ return encodedData;\r
+ }\r
+\r
+ /**\r
+ * Decodes Base64 data into octects\r
+ *\r
+ * @param base64Data Byte array containing Base64 data\r
+ * @return Array containing decoded data.\r
+ */\r
+ public static byte[] decodeBase64(byte[] base64Data) {\r
+ // RFC 2045 requires that we discard ALL non-Base64 characters\r
+ base64Data = discardNonBase64(base64Data);\r
+\r
+ // handle the edge case, so we don't have to worry about it later\r
+ if (base64Data.length == 0) {\r
+ return new byte[0];\r
+ }\r
+\r
+ int numberQuadruple = base64Data.length / FOURBYTE;\r
+ byte decodedData[] = null;\r
+ byte b1 = 0, b2 = 0, b3 = 0, b4 = 0, marker0 = 0, marker1 = 0;\r
+\r
+ // Throw away anything not in base64Data\r
+\r
+ int encodedIndex = 0;\r
+ int dataIndex = 0;\r
+ {\r
+ // this sizes the output array properly - rlw\r
+ int lastData = base64Data.length;\r
+ // ignore the '=' padding\r
+ while (base64Data[lastData - 1] == PAD) {\r
+ if (--lastData == 0) {\r
+ return new byte[0];\r
+ }\r
+ }\r
+ decodedData = new byte[lastData - numberQuadruple];\r
+ }\r
+ \r
+ for (int i = 0; i < numberQuadruple; i++) {\r
+ dataIndex = i * 4;\r
+ marker0 = base64Data[dataIndex + 2];\r
+ marker1 = base64Data[dataIndex + 3];\r
+ \r
+ b1 = base64Alphabet[base64Data[dataIndex]];\r
+ b2 = base64Alphabet[base64Data[dataIndex + 1]];\r
+ \r
+ if (marker0 != PAD && marker1 != PAD) {\r
+ //No PAD e.g 3cQl\r
+ b3 = base64Alphabet[marker0];\r
+ b4 = base64Alphabet[marker1];\r
+ \r
+ decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);\r
+ decodedData[encodedIndex + 1] =\r
+ (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));\r
+ decodedData[encodedIndex + 2] = (byte) (b3 << 6 | b4);\r
+ } else if (marker0 == PAD) {\r
+ //Two PAD e.g. 3c[Pad][Pad]\r
+ decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);\r
+ } else if (marker1 == PAD) {\r
+ //One PAD e.g. 3cQ[Pad]\r
+ b3 = base64Alphabet[marker0];\r
+ \r
+ decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);\r
+ decodedData[encodedIndex + 1] =\r
+ (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));\r
+ }\r
+ encodedIndex += 3;\r
+ }\r
+ return decodedData;\r
+ }\r
+ \r
+ /**\r
+ * Discards any whitespace from a base-64 encoded block.\r
+ *\r
+ * @param data The base-64 encoded data to discard the whitespace\r
+ * from.\r
+ * @return The data, less whitespace (see RFC 2045).\r
+ */\r
+ static byte[] discardWhitespace(byte[] data) {\r
+ byte groomedData[] = new byte[data.length];\r
+ int bytesCopied = 0;\r
+ \r
+ for (int i = 0; i < data.length; i++) {\r
+ switch (data[i]) {\r
+ case (byte) ' ' :\r
+ case (byte) '\n' :\r
+ case (byte) '\r' :\r
+ case (byte) '\t' :\r
+ break;\r
+ default:\r
+ groomedData[bytesCopied++] = data[i];\r
+ }\r
+ }\r
+\r
+ byte packedData[] = new byte[bytesCopied];\r
+\r
+ System.arraycopy(groomedData, 0, packedData, 0, bytesCopied);\r
+\r
+ return packedData;\r
+ }\r
+\r
+ /**\r
+ * Discards any characters outside of the base64 alphabet, per\r
+ * the requirements on page 25 of RFC 2045 - "Any characters\r
+ * outside of the base64 alphabet are to be ignored in base64\r
+ * encoded data."\r
+ *\r
+ * @param data The base-64 encoded data to groom\r
+ * @return The data, less non-base64 characters (see RFC 2045).\r
+ */\r
+ static byte[] discardNonBase64(byte[] data) {\r
+ byte groomedData[] = new byte[data.length];\r
+ int bytesCopied = 0;\r
+\r
+ for (int i = 0; i < data.length; i++) {\r
+ if (isBase64(data[i])) {\r
+ groomedData[bytesCopied++] = data[i];\r
+ }\r
+ }\r
+\r
+ byte packedData[] = new byte[bytesCopied];\r
+\r
+ System.arraycopy(groomedData, 0, packedData, 0, bytesCopied);\r
+\r
+ return packedData;\r
+ }\r
+\r
+\r
+ // Implementation of the Encoder Interface\r
+\r
+ /**\r
+ * Encodes an Object using the base64 algorithm. This method\r
+ * is provided in order to satisfy the requirements of the\r
+ * Encoder interface, and will throw an EncoderException if the\r
+ * supplied object is not of type byte[].\r
+ *\r
+ * @param pObject Object to encode\r
+ * @return An object (of type byte[]) containing the \r
+ * base64 encoded data which corresponds to the byte[] supplied.\r
+ * @throws EncoderException if the parameter supplied is not\r
+ * of type byte[]\r
+ */\r
+ public Object encode(Object pObject) throws EncoderException {\r
+ if (!(pObject instanceof byte[])) {\r
+ throw new EncoderException(\r
+ "Parameter supplied to Base64 encode is not a byte[]");\r
+ }\r
+ return encode((byte[]) pObject);\r
+ }\r
+\r
+ /**\r
+ * Encodes a byte[] containing binary data, into a byte[] containing\r
+ * characters in the Base64 alphabet.\r
+ *\r
+ * @param pArray a byte array containing binary data\r
+ * @return A byte array containing only Base64 character data\r
+ */\r
+ public byte[] encode(byte[] pArray) {\r
+ return encodeBase64(pArray, false);\r
+ }\r
+\r
+}\r