001: // Copyright (C) 1999-2002 by Jason Hunter <jhunter_AT_acm_DOT_org>.
002: // All rights reserved. Use of this class is limited.
003: // Please see the LICENSE for more information.
004:
005: package com.knowgate.misc;
006:
007: import java.io.*;
008:
009: /**
010: * <p>A class to decode Base64 streams and strings.</p>
011: * <p>See RFC 1521 section 5.2 for details of the Base64 algorithm.</p>
012: * <p>
013: * This class can be used for decoding strings:
014: * <blockquote><pre>
015: * String encoded = "d2VibWFzdGVyOnRyeTJndWVTUw";
016: * String decoded = Base64Decoder.decode(encoded);
017: * </pre></blockquote>
018: * or for decoding streams:
019: * <blockquote><pre>
020: * InputStream in = new Base64Decoder(System.in);
021: * </pre></blockquote>
022: *
023: * @author <b>Jason Hunter</b>, Copyright © 2000
024: * @version 1.1, 2002/11/01, added decodeToBytes() to better handle binary
025: * data (thanks to Sean Graham)
026: * @version 1.0, 2000/06/11
027: */
028: public class Base64Decoder extends FilterInputStream {
029:
030: private static final char[] chars = { 'A', 'B', 'C', 'D', 'E', 'F',
031: 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
032: 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
033: 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
034: 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1',
035: '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' };
036:
037: // A mapping between char values and six-bit integers
038: private static final int[] ints = new int[128];
039: static {
040: for (int i = 0; i < 64; i++) {
041: ints[chars[i]] = i;
042: }
043: }
044:
045: private int charCount;
046: private int carryOver;
047:
048: /**
049: * Constructs a new Base64 decoder that reads input from the given
050: * InputStream.
051: *
052: * @param in the input stream
053: */
054: public Base64Decoder(InputStream in) {
055: super (in);
056: }
057:
058: /**
059: * Returns the next decoded character from the stream, or -1 if
060: * end of stream was reached.
061: *
062: * @return the decoded character, or -1 if the end of the
063: * input stream is reached
064: * @exception IOException if an I/O error occurs
065: */
066: public int read() throws IOException {
067: // Read the next non-whitespace character
068: int x;
069: do {
070: x = in.read();
071: if (x == -1) {
072: return -1;
073: }
074: } while (Character.isWhitespace((char) x));
075: charCount++;
076:
077: // The '=' sign is just padding
078: if (x == '=') {
079: return -1; // effective end of stream
080: }
081:
082: // Convert from raw form to 6-bit form
083: x = ints[x];
084:
085: // Calculate which character we're decoding now
086: int mode = (charCount - 1) % 4;
087:
088: // First char save all six bits, go for another
089: if (mode == 0) {
090: carryOver = x & 63;
091: return read();
092: }
093: // Second char use previous six bits and first two new bits,
094: // save last four bits
095: else if (mode == 1) {
096: int decoded = ((carryOver << 2) + (x >> 4)) & 255;
097: carryOver = x & 15;
098: return decoded;
099: }
100: // Third char use previous four bits and first four new bits,
101: // save last two bits
102: else if (mode == 2) {
103: int decoded = ((carryOver << 4) + (x >> 2)) & 255;
104: carryOver = x & 3;
105: return decoded;
106: }
107: // Fourth char use previous two bits and all six new bits
108: else if (mode == 3) {
109: int decoded = ((carryOver << 6) + x) & 255;
110: return decoded;
111: }
112: return -1; // can't actually reach this line
113: }
114:
115: /**
116: * Reads decoded data into an array of bytes and returns the actual
117: * number of bytes read, or -1 if end of stream was reached.
118: *
119: * @param buf the buffer into which the data is read
120: * @param off the start offset of the data
121: * @param len the maximum number of bytes to read
122: * @return the actual number of bytes read, or -1 if the end of the
123: * input stream is reached
124: * @exception IOException if an I/O error occurs
125: */
126: public int read(byte[] buf, int off, int len) throws IOException {
127: if (buf.length < (len + off - 1)) {
128: throw new IOException("The input buffer is too small: "
129: + len + " bytes requested starting at offset "
130: + off + " while the buffer " + " is only "
131: + buf.length + " bytes long.");
132: }
133:
134: // This could of course be optimized
135: int i;
136: for (i = 0; i < len; i++) {
137: int x = read();
138: if (x == -1 && i == 0) { // an immediate -1 returns -1
139: return -1;
140: } else if (x == -1) { // a later -1 returns the chars read so far
141: break;
142: }
143: buf[off + i] = (byte) x;
144: }
145: return i;
146: }
147:
148: /**
149: * Returns the decoded form of the given encoded string, as a String.
150: * Note that not all binary data can be represented as a String, so this
151: * method should only be used for encoded String data. Use decodeToBytes()
152: * otherwise.
153: *
154: * @param encoded the string to decode
155: * @return the decoded form of the encoded string
156: */
157: public static String decode(String encoded) {
158: return new String(decodeToBytes(encoded));
159: }
160:
161: /**
162: * Returns the decoded form of the given encoded string, as bytes.
163: *
164: * @param encoded the string to decode
165: * @return the decoded form of the encoded string
166: */
167: public static byte[] decodeToBytes(String encoded) {
168: byte[] bytes = null;
169: try {
170: bytes = encoded.getBytes("8859_1");
171: } catch (UnsupportedEncodingException ignored) {
172: }
173:
174: Base64Decoder in = new Base64Decoder(new ByteArrayInputStream(
175: bytes));
176:
177: ByteArrayOutputStream out = new ByteArrayOutputStream(
178: (int) (bytes.length * 0.67));
179:
180: try {
181: byte[] buf = new byte[4 * 1024]; // 4K buffer
182: int bytesRead;
183: while ((bytesRead = in.read(buf)) != -1) {
184: out.write(buf, 0, bytesRead);
185: }
186: out.close();
187:
188: return out.toByteArray();
189: } catch (IOException ignored) {
190: return null;
191: }
192: }
193:
194: public static void main(String[] args) throws Exception {
195: if (args.length != 1) {
196: System.err
197: .println("Usage: java Base64Decoder fileToDecode");
198: return;
199: }
200:
201: Base64Decoder decoder = null;
202: try {
203: decoder = new Base64Decoder(new BufferedInputStream(
204: new FileInputStream(args[0])));
205: byte[] buf = new byte[4 * 1024]; // 4K buffer
206: int bytesRead;
207: while ((bytesRead = decoder.read(buf)) != -1) {
208: System.out.write(buf, 0, bytesRead);
209: }
210: } finally {
211: if (decoder != null)
212: decoder.close();
213: }
214: }
215: }
|