diff options
Diffstat (limited to 'gnu/java')
| -rw-r--r-- | gnu/java/net/BASE64.java | 190 | ||||
| -rw-r--r-- | gnu/java/net/protocol/http/Request.java | 6 | ||||
| -rw-r--r-- | gnu/java/security/util/Base64.java | 349 | ||||
| -rw-r--r-- | gnu/java/util/Base64.java | 340 |
4 files changed, 343 insertions, 542 deletions
diff --git a/gnu/java/net/BASE64.java b/gnu/java/net/BASE64.java deleted file mode 100644 index 901aa0c35..000000000 --- a/gnu/java/net/BASE64.java +++ /dev/null @@ -1,190 +0,0 @@ -/* BASE.java -- - Copyright (C) 2003, 2004, 2005 Free Software Foundation, Inc. - -This file is part of GNU Classpath. - -GNU Classpath is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2, or (at your option) -any later version. - -GNU Classpath is distributed in the hope that it will be useful, but -WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -General Public License for more details. - -You should have received a copy of the GNU General Public License -along with GNU Classpath; see the file COPYING. If not, write to the -Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA -02110-1301 USA. - -Linking this library statically or dynamically with other modules is -making a combined work based on this library. Thus, the terms and -conditions of the GNU General Public License cover the whole -combination. - -As a special exception, the copyright holders of this library give you -permission to link this library with independent modules to produce an -executable, regardless of the license terms of these independent -modules, and to copy and distribute the resulting executable under -terms of your choice, provided that you also meet, for each linked -independent module, the terms and conditions of the license of that -module. An independent module is a module which is not derived from -or based on this library. If you modify this library, you may extend -this exception to your version of the library, but you are not -obligated to do so. If you do not wish to do so, delete this -exception statement from your version. */ - - -package gnu.java.net; - -/** - * Encodes and decodes text according to the BASE64 encoding. - * - * @author Chris Burdess (dog@gnu.org) - */ -public final class BASE64 -{ - private static final byte[] src = { - 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, - 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, - 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x61, 0x62, 0x63, 0x64, - 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, - 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, - 0x79, 0x7a, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, - 0x38, 0x39, 0x2b, 0x2f - }; - - private static final byte[] dst; - static - { - dst = new byte[0x100]; - for (int i = 0x0; i < 0xff; i++) - { - dst[i] = -1; - } - for (int i = 0; i < src.length; i++) - { - dst[src[i]] = (byte) i; - } - } - - private BASE64() - { - } - - /** - * Encode the specified byte array using the BASE64 algorithm. - * - * @param bs the source byte array - */ - public static byte[] encode(byte[] bs) - { - int si = 0, ti = 0; // source/target array indices - byte[] bt = new byte[((bs.length + 2) * 4) / 3]; // target byte array - for (; si < bs.length; si += 3) - { - int buflen = bs.length - si; - if (buflen == 1) - { - byte b = bs[si]; - int i = 0; - bt[ti++] = src[b >>> 2 & 0x3f]; - bt[ti++] = src[(b << 4 & 0x30) + (i >>> 4 & 0xf)]; - } - else if (buflen == 2) - { - byte b1 = bs[si], b2 = bs[si + 1]; - int i = 0; - bt[ti++] = src[b1 >>> 2 & 0x3f]; - bt[ti++] = src[(b1 << 4 & 0x30) + (b2 >>> 4 & 0xf)]; - bt[ti++] = src[(b2 << 2 & 0x3c) + (i >>> 6 & 0x3)]; - } - else - { - byte b1 = bs[si], b2 = bs[si + 1], b3 = bs[si + 2]; - bt[ti++] = src[b1 >>> 2 & 0x3f]; - bt[ti++] = src[(b1 << 4 & 0x30) + (b2 >>> 4 & 0xf)]; - bt[ti++] = src[(b2 << 2 & 0x3c) + (b3 >>> 6 & 0x3)]; - bt[ti++] = src[b3 & 0x3f]; - } - } - if (ti < bt.length) - { - byte[] tmp = new byte[ti]; - System.arraycopy(bt, 0, tmp, 0, ti); - bt = tmp; - } - /*while (ti < bt.length) - { - bt[ti++] = 0x3d; - }*/ - return bt; - } - - /** - * Decode the specified byte array using the BASE64 algorithm. - * - * @param bs the source byte array - */ - public static byte[] decode(byte[] bs) - { - int srclen = bs.length; - while (srclen > 0 && bs[srclen - 1] == 0x3d) - { - srclen--; /* strip padding character */ - } - byte[] buffer = new byte[srclen]; - int buflen = 0; - int si = 0; - int len = srclen - si; - while (len > 0) - { - byte b0 = dst[bs[si++] & 0xff]; - byte b2 = dst[bs[si++] & 0xff]; - buffer[buflen++] = (byte) (b0 << 2 & 0xfc | b2 >>> 4 & 0x3); - if (len > 2) - { - b0 = b2; - b2 = dst[bs[si++] & 0xff]; - buffer[buflen++] = (byte) (b0 << 4 & 0xf0 | b2 >>> 2 & 0xf); - if (len > 3) - { - b0 = b2; - b2 = dst[bs[si++] & 0xff]; - buffer[buflen++] = (byte) (b0 << 6 & 0xc0 | b2 & 0x3f); - } - } - len = srclen - si; - } - byte[] bt = new byte[buflen]; - System.arraycopy(buffer, 0, bt, 0, buflen); - return bt; - } - - public static void main(String[] args) - { - boolean decode = false; - for (int i = 0; i < args.length; i++) - { - if (args[i].equals("-d")) - { - decode = true; - } - else - { - try - { - byte[] in = args[i].getBytes("US-ASCII"); - byte[] out = decode ? decode(in) : encode(in); - System.out.println(args[i] + " = " + - new String(out, "US-ASCII")); - } - catch (java.io.UnsupportedEncodingException e) - { - e.printStackTrace(System.err); - } - } - } - } -} diff --git a/gnu/java/net/protocol/http/Request.java b/gnu/java/net/protocol/http/Request.java index d1ebf700e..06a779f33 100644 --- a/gnu/java/net/protocol/http/Request.java +++ b/gnu/java/net/protocol/http/Request.java @@ -1,5 +1,5 @@ /* Request.java -- - Copyright (C) 2004, 2005, 2006 Free Software Foundation, Inc. + Copyright (C) 2004, 2005, 2006, 2007 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -38,8 +38,8 @@ exception statement from your version. */ package gnu.java.net.protocol.http; -import gnu.java.net.BASE64; import gnu.java.net.LineInputStream; +import gnu.java.util.Base64; import java.io.IOException; import java.io.InputStream; @@ -529,7 +529,7 @@ public class Request Credentials creds = authenticator.getCredentials(realm, attempts); String userPass = creds.getUsername() + ':' + creds.getPassword(); byte[] b_userPass = userPass.getBytes("US-ASCII"); - byte[] b_encoded = BASE64.encode(b_userPass); + byte[] b_encoded = Base64.encode(b_userPass).getBytes("US-ASCII"); String authorization = scheme + " " + new String(b_encoded, "US-ASCII"); setHeader("Authorization", authorization); diff --git a/gnu/java/security/util/Base64.java b/gnu/java/security/util/Base64.java deleted file mode 100644 index 9b2ae12dc..000000000 --- a/gnu/java/security/util/Base64.java +++ /dev/null @@ -1,349 +0,0 @@ -/* Base64.java -- - Copyright (C) 2003, 2006 Free Software Foundation, Inc. - -This file is a part of GNU Classpath. - -GNU Classpath is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or (at -your option) any later version. - -GNU Classpath is distributed in the hope that it will be useful, but -WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -General Public License for more details. - -You should have received a copy of the GNU General Public License -along with GNU Classpath; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 -USA - -Linking this library statically or dynamically with other modules is -making a combined work based on this library. Thus, the terms and -conditions of the GNU General Public License cover the whole -combination. - -As a special exception, the copyright holders of this library give you -permission to link this library with independent modules to produce an -executable, regardless of the license terms of these independent -modules, and to copy and distribute the resulting executable under -terms of your choice, provided that you also meet, for each linked -independent module, the terms and conditions of the license of that -module. An independent module is a module which is not derived from -or based on this library. If you modify this library, you may extend -this exception to your version of the library, but you are not -obligated to do so. If you do not wish to do so, delete this -exception statement from your version. */ - - -package gnu.java.security.util; - -import gnu.java.security.Configuration; - -import java.io.UnsupportedEncodingException; -import java.util.logging.Logger; - -/** - * Most of this implementation is from Robert Harder's public domain Base64 - * code (version 1.4.1 available from <http://iharder.net/xmlizable>). - */ -public class Base64 -{ - private static final Logger log = Logger.getLogger(Base64.class.getName()); - - /** Maximum line length (76) of Base64 output. */ - private static final int MAX_LINE_LENGTH = 76; - - /** The new line character (\n) as one byte. */ - private static final byte NEW_LINE = (byte) '\n'; - - /** The equals sign (=) as a byte. */ - private static final byte EQUALS_SIGN = (byte) '='; - - private static final byte WHITE_SPACE_ENC = -5; // white space in encoding - - private static final byte EQUALS_SIGN_ENC = -1; // equals sign in encoding - - /** The 64 valid Base64 values. */ - private static final byte[] ALPHABET = { - (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', - (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', - (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', - (byte) 'S', (byte) 'T', (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', - (byte) 'Y', (byte) 'Z', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', - (byte) 'e', (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j', - (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p', - (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', (byte) 'v', - (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', (byte) '0', (byte) '1', - (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', - (byte) '8', (byte) '9', (byte) '+', (byte) '/' - }; - - /** - * Translates a Base64 value to either its 6-bit reconstruction value or a - * negative number indicating some other meaning. - */ - private static final byte[] DECODABET = { - -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 - -5, -5, // Whitespace: Tab and Linefeed - -9, -9, // Decimal 11 - 12 - -5, // Whitespace: Carriage Return - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26 - -9, -9, -9, -9, -9, // Decimal 27 - 31 - -5, // Whitespace: Space - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42 - 62, // Plus sign at decimal 43 - -9, -9, -9, // Decimal 44 - 46 - 63, // Slash at decimal 47 - 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine - -9, -9, -9, // Decimal 58 - 60 - -1, // Equals sign at decimal 61 - -9, -9, -9, // Decimal 62 - 64 - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N' - 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z' - -9, -9, -9, -9, -9, -9, // Decimal 91 - 96 - 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm' - 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z' - -9, -9, -9, -9 // Decimal 123 - 126 - }; - - /** Trivial private ctor to enfore Singleton pattern. */ - private Base64() - { - super(); - } - - /** - * Encodes a byte array into Base64 notation. Equivalent to calling - * <code>encode(source, 0, source.length)</code>. - * - * @param src the data to convert. - */ - public static final String encode(final byte[] src) - { - return encode(src, 0, src.length, true); - } - - /** - * Encodes a byte array into Base64 notation. - * - * @param src the data to convert. - * @param off offset in array where conversion should begin. - * @param len length of data to convert. - * @param breakLines break lines at 80 characters or less. - */ - public static final String encode(final byte[] src, final int off, - final int len, final boolean breakLines) - { - final int len43 = len * 4 / 3; - final byte[] outBuff = new byte[len43 // Main 4:3 - + ((len % 3) > 0 ? 4 : 0) // Account for padding - + (breakLines ? (len43 / MAX_LINE_LENGTH) - : 0)]; // New lines - int d = 0; - int e = 0; - final int len2 = len - 2; - int lineLength = 0; - for (; d < len2; d += 3, e += 4) - { - encode3to4(src, d + off, 3, outBuff, e); - lineLength += 4; - if (breakLines && lineLength == MAX_LINE_LENGTH) - { - outBuff[e + 4] = NEW_LINE; - e++; - lineLength = 0; - } - } - if (d < len) // padding needed - { - encode3to4(src, d + off, len - d, outBuff, e); - e += 4; - } - return new String(outBuff, 0, e); - } - - /** - * Decodes data from Base64 notation. - * - * @param s the string to decode. - * @return the decoded data. - */ - public static final byte[] decode(final String s) - throws UnsupportedEncodingException - { - final byte[] bytes; - bytes = s.getBytes("US-ASCII"); - return decode(bytes, 0, bytes.length); - } - - /** - * Decodes Base64 content in byte array format and returns the decoded byte - * array. - * - * @param src the Base64 encoded data. - * @param off the offset of where to begin decoding. - * @param len the length of characters to decode. - * @return the decoded data. - * @throws IllegalArgumentException if <code>src</code> contains an illegal - * Base-64 character. - */ - public static byte[] decode(final byte[] src, final int off, final int len) - { - final int len34 = len * 3 / 4; - final byte[] outBuff = new byte[len34]; // Upper limit on size of output - int outBuffPosn = 0; - final byte[] b4 = new byte[4]; - int b4Posn = 0; - int i; - byte sbiCrop, sbiDecode; - for (i = off; i < off + len; i++) - { - sbiCrop = (byte) (src[i] & 0x7F); // Only the low seven bits - sbiDecode = DECODABET[sbiCrop]; - if (sbiDecode >= WHITE_SPACE_ENC) - { // White space, Equals sign or better - if (sbiDecode >= EQUALS_SIGN_ENC) - { - b4[b4Posn++] = sbiCrop; - if (b4Posn > 3) - { - outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn); - b4Posn = 0; - // If that was the equals sign, break out of 'for' loop - if (sbiCrop == EQUALS_SIGN) - break; - } // end if: quartet built - } // end if: equals sign or better - } - throw new IllegalArgumentException("Illegal BASE-64 character at #" - + i + ": " + src[i] + "(decimal)"); - } - final byte[] result = new byte[outBuffPosn]; - System.arraycopy(outBuff, 0, result, 0, outBuffPosn); - return result; - } - - /** - * Encodes up to three bytes of the array <code>src</code> and writes the - * resulting four Base64 bytes to <code>dest</code>. The source and - * destination arrays can be manipulated anywhere along their length by - * specifying <code>sOffset</code> and <code>dOffset</code>. - * <p> - * This method does not check to make sure the arrays are large enough to - * accomodate <code>sOffset + 3</code> for the <code>src</code> array or - * <code>dOffset + 4</code> for the <code>dest</code> array. The actual - * number of significant bytes in the input array is given by - * <code>numBytes</code>. - * - * @param src the array to convert. - * @param sOffset the index where conversion begins. - * @param numBytes the number of significant bytes in your array. - * @param dest the array to hold the conversion. - * @param dOffset the index where output will be put. - * @return the <code>destination</code> array. - */ - private static final byte[] encode3to4(final byte[] src, final int sOffset, - final int numBytes, final byte[] dest, - final int dOffset) - { - // 1 2 3 - // 01234567890123456789012345678901 Bit position - // --------000000001111111122222222 Array position from threeBytes - // --------| || || || | Six bit groups to index ALPHABET - // >>18 >>12 >> 6 >> 0 Right shift necessary - // 0x3F 0x3F 0x3F Additional AND - - // Create buffer with zero-padding if there are only one or two - // significant bytes passed in the array. - // We have to shift left 24 in order to flush out the 1's that appear - // when Java treats a value as negative that is cast from a byte to an int. - final int inBuff = (numBytes > 0 ? ((src[sOffset] << 24) >>> 8) : 0) - | (numBytes > 1 ? ((src[sOffset + 1] << 24) >>> 16) : 0) - | (numBytes > 2 ? ((src[sOffset + 2] << 24) >>> 24) : 0); - switch (numBytes) - { - case 3: - dest[dOffset ] = ALPHABET[(inBuff >>> 18)]; - dest[dOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3F]; - dest[dOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3F]; - dest[dOffset + 3] = ALPHABET[(inBuff) & 0x3F]; - break; - case 2: - dest[dOffset ] = ALPHABET[(inBuff >>> 18)]; - dest[dOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3F]; - dest[dOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3F]; - dest[dOffset + 3] = EQUALS_SIGN; - break; - case 1: - dest[dOffset ] = ALPHABET[(inBuff >>> 18)]; - dest[dOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3F]; - dest[dOffset + 2] = EQUALS_SIGN; - dest[dOffset + 3] = EQUALS_SIGN; - break; - } - return dest; - } - - /** - * Decodes four bytes from array <code>src</code> and writes the resulting - * bytes (up to three of them) to <code>dest</code>. - * <p> - * The source and destination arrays can be manipulated anywhere along their - * length by specifying <code>sOffset</code> and <code>dOffset</code>. - * <p> - * This method does not check to make sure your arrays are large enough to - * accomodate <code>sOffset + 4</code> for the <code>src</code> array or - * <code>dOffset + 3</code> for the <code>dest</code> array. This method - * returns the actual number of bytes that were converted from the Base64 - * encoding. - * - * @param src the array to convert. - * @param sOffset the index where conversion begins. - * @param dest the array to hold the conversion. - * @param dOffset the index where output will be put. - * @return the number of decoded bytes converted. - */ - private static final int decode4to3(final byte[] src, final int sOffset, - final byte[] dest, final int dOffset) - { - if (src[sOffset + 2] == EQUALS_SIGN) // Example: Dk== - { - final int outBuff = ((DECODABET[src[sOffset ]] & 0xFF) << 18) - | ((DECODABET[src[sOffset + 1]] & 0xFF) << 12); - dest[dOffset] = (byte)(outBuff >>> 16); - return 1; - } - if (src[sOffset + 3] == EQUALS_SIGN) // Example: DkL= - { - final int outBuff = ((DECODABET[src[sOffset ]] & 0xFF) << 18) - | ((DECODABET[src[sOffset + 1]] & 0xFF) << 12) - | ((DECODABET[src[sOffset + 2]] & 0xFF) << 6); - dest[dOffset ] = (byte)(outBuff >>> 16); - dest[dOffset + 1] = (byte)(outBuff >>> 8); - return 2; - } - try // Example: DkLE - { - final int outBuff = ((DECODABET[src[sOffset ]] & 0xFF) << 18) - | ((DECODABET[src[sOffset + 1]] & 0xFF) << 12) - | ((DECODABET[src[sOffset + 2]] & 0xFF) << 6) - | ((DECODABET[src[sOffset + 3]] & 0xFF)); - dest[dOffset ] = (byte)(outBuff >> 16); - dest[dOffset + 1] = (byte)(outBuff >> 8); - dest[dOffset + 2] = (byte) outBuff; - return 3; - } - catch (Exception x) - { - if (Configuration.DEBUG) - { - log.fine("" + src[sOffset ] + ": " + (DECODABET[src[sOffset ]])); - log.fine("" + src[sOffset + 1] + ": " + (DECODABET[src[sOffset + 1]])); - log.fine("" + src[sOffset + 2] + ": " + (DECODABET[src[sOffset + 2]])); - log.fine("" + src[sOffset + 3] + ": " + (DECODABET[src[sOffset + 3]])); - } - return -1; - } - } -} diff --git a/gnu/java/util/Base64.java b/gnu/java/util/Base64.java new file mode 100644 index 000000000..592696bcc --- /dev/null +++ b/gnu/java/util/Base64.java @@ -0,0 +1,340 @@ +/* Base64.java -- Base64 encoding and decoding. + Copyright (C) 2006, 2007 Free Software Foundation, Inc. + +This file is a part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or (at +your option) any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 +USA + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. + +-- +Base64 encoding derived from ISC's DHCP. Copyright notices from DHCP +follow. See http://www.isc.org/products/DHCP/. + +Copyright (c) 1996 by Internet Software Consortium. + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM +DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL +INTERNET SOFTWARE CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING +FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, +NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION +WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +-- +Portions Copyright (c) 1995 by International Business Machines, Inc. + +International Business Machines, Inc. (hereinafter called IBM) grants +permission under its copyrights to use, copy, modify, and distribute +this Software with or without fee, provided that the above copyright +notice and all paragraphs of this notice appear in all copies, and +that the name of IBM not be used in connection with the marketing of +any product incorporating the Software or modifications thereof, +without specific, written prior permission. + +To the extent it has a right to do so, IBM grants an immunity from +suit under its patents, if any, for the use, sale or manufacture of +products to the extent that such products are used for performing +Domain Name System dynamic updates in TCP/IP networks by means of the +Software. No immunity is granted for any product per se or for any +other function of any product. + +THE SOFTWARE IS PROVIDED "AS IS", AND IBM DISCLAIMS ALL WARRANTIES, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE. IN NO EVENT SHALL IBM BE LIABLE FOR ANY SPECIAL, +DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS +SOFTWARE, EVEN IF IBM IS APPRISED OF THE POSSIBILITY OF SUCH +DAMAGES. */ + + +package gnu.java.util; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +public final class Base64 +{ + + // No constructor. + private Base64() { } + + // Class methods. + // ------------------------------------------------------------------------- + + /** Base-64 characters. */ + private static final String BASE_64 = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + + /** Base-64 padding character. */ + private static final char BASE_64_PAD = '='; + + /** + * Base64 encode a byte array, with no line wrapping. + * + * @param buf The byte array to encode. + * @return <tt>buf</tt> encoded in Base64. + */ + public static String encode(byte[] buf) + { + return encode(buf, 0); + } + + /** + * Base64 encode a byte array, returning the returning string. + * + * @param buf The byte array to encode. + * @param tw The total length of any line, 0 for unlimited. + * @return <tt>buf</tt> encoded in Base64. + */ + public static String encode(byte[] buf, int tw) + { + return encode(buf, 0, buf.length, tw); + } + + /** + * Base64 encode a byte array, returning the returning string. + * + * @param buf The byte array to encode. + * @param offset The offset in the byte array to start. + * @param length The number of bytes to encode. + * @param tw The total length of any line, 0 for unlimited. + * @return <tt>buf</tt> encoded in Base64. + */ + public static String encode(byte[] buf, int offset, int length, int tw) + { + if (offset < 0 || length < 0 || offset + length > buf.length) + throw new ArrayIndexOutOfBoundsException(buf.length + " " + + offset + " " + + length); + int srcLength = buf.length - offset; + byte[] input = new byte[3]; + int[] output = new int[4]; + StringBuffer out = new StringBuffer(); + int i = offset; + int chars = 0; + + while (srcLength > 2) + { + input[0] = buf[i++]; + input[1] = buf[i++]; + input[2] = buf[i++]; + srcLength -= 3; + + output[0] = (input[0] & 0xff) >>> 2; + output[1] = ((input[0] & 0x03) << 4) + ((input[1] & 0xff) >>> 4); + output[2] = ((input[1] & 0x0f) << 2) + ((input[2] & 0xff) >>> 6); + output[3] = input[2] & 0x3f; + + out.append(BASE_64.charAt(output[0])); + if (tw > 0 && ++chars % tw == 0) + { + out.append("\n"); + } + out.append(BASE_64.charAt(output[1])); + if (tw > 0 && ++chars % tw == 0) + { + out.append("\n"); + } + out.append(BASE_64.charAt(output[2])); + if (tw > 0 && ++chars % tw == 0) + { + out.append("\n"); + } + out.append(BASE_64.charAt(output[3])); + if (tw > 0 && ++chars % tw == 0) + { + out.append("\n"); + } + } + + if (srcLength != 0) + { + input[0] = input[1] = input[2] = 0; + for (int j = 0; j < srcLength; j++) + { + input[j] = buf[i+j]; + } + output[0] = (input[0] & 0xff) >>> 2; + output[1] = ((input[0] & 0x03) << 4) + ((input[1] & 0xff) >>> 4); + output[2] = ((input[1] & 0x0f) << 2) + ((input[2] & 0xff) >>> 6); + + out.append(BASE_64.charAt(output[0])); + if (tw > 0 && ++chars % tw == 0) + { + out.append("\n"); + } + out.append(BASE_64.charAt(output[1])); + if (tw > 0 && ++chars % tw == 0) + { + out.append("\n"); + } + if (srcLength == 1) + { + out.append(BASE_64_PAD); + } + else + { + out.append(BASE_64.charAt(output[2])); + } + if (tw > 0 && ++chars % tw == 0) + { + out.append("\n"); + } + out.append(BASE_64_PAD); + if (tw > 0 && ++chars % tw == 0) + { + out.append("\n"); + } + } + if (tw > 0) + { + out.append("\n"); + } + + return out.toString(); + } + + /** + * Decode a Base-64 string into a byte array. + * + * @param b64 The Base-64 encoded string. + * @return The decoded bytes. + * @throws java.io.IOException If the argument is not a valid Base-64 + * encoding. + */ + public static byte[] decode(String b64) throws IOException + { + ByteArrayOutputStream result = new ByteArrayOutputStream(b64.length() / 3); + int state = 0, i; + byte temp = 0; + + for (i = 0; i < b64.length(); i++) + { + if (Character.isWhitespace(b64.charAt(i))) + { + continue; + } + if (b64.charAt(i) == BASE_64_PAD) + { + break; + } + + int pos = BASE_64.indexOf(b64.charAt(i)); + if (pos < 0) + { + throw new IOException("non-Base64 character " + b64.charAt(i)); + } + switch (state) + { + case 0: + temp = (byte) (pos - BASE_64.indexOf('A') << 2); + state = 1; + break; + + case 1: + temp |= (byte) (pos - BASE_64.indexOf('A') >>> 4); + result.write(temp); + temp = (byte) ((pos - BASE_64.indexOf('A') & 0x0f) << 4); + state = 2; + break; + + case 2: + temp |= (byte) ((pos - BASE_64.indexOf('A') & 0x7f) >>> 2); + result.write(temp); + temp = (byte) ((pos - BASE_64.indexOf('A') & 0x03) << 6); + state = 3; + break; + + case 3: + temp |= (byte) (pos - BASE_64.indexOf('A') & 0xff); + result.write(temp); + state = 0; + break; + + default: + throw new Error("this statement should be unreachable"); + } + } + + if (i < b64.length() && b64.charAt(i) == BASE_64_PAD) + { + switch (state) + { + case 0: + case 1: + throw new IOException("malformed Base64 sequence"); + + case 2: + i++; + for ( ; i < b64.length(); i++) + { + if (!Character.isWhitespace(b64.charAt(i))) + { + break; + } + } + // We must see a second pad character here. + if (b64.charAt(i) != BASE_64_PAD) + { + throw new IOException("malformed Base64 sequence"); + } + i++; + // Fall-through. + + case 3: + i++; + for ( ; i < b64.length(); i++) + { + // We should only see whitespace after this. + if (!Character.isWhitespace(b64.charAt(i))) + { + throw new IOException("malformed Base64 sequence"); + } + } + } + } + else + { + if (state != 0) + { + throw new IOException("malformed Base64 sequence"); + } + } + + return result.toByteArray(); + } +} |
