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 encode 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 encoding strings:
014: * <blockquote><pre>
015: * String unencoded = "webmaster:try2gueSS";
016: * String encoded = Base64Encoder.encode(unencoded);
017: * </pre></blockquote>
018: * or for encoding streams:
019: * <blockquote><pre>
020: * OutputStream out = new Base64Encoder(System.out);
021: * </pre></blockquote>
022: *
023: * @author <b>Jason Hunter</b>, Copyright © 2000
024: * @version 1.2, 2002/11/01, added encode(byte[]) method to better handle
025: * binary data (thanks to Sean Graham)
026: * @version 1.1, 2000/11/17, fixed bug with sign bit for char values
027: * @version 1.0, 2000/06/11
028: */
029: public class Base64Encoder extends FilterOutputStream {
030:
031: private static final char[] chars = { 'A', 'B', 'C', 'D', 'E', 'F',
032: 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
033: 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
034: 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
035: 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1',
036: '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' };
037:
038: private int charCount;
039: private int carryOver;
040:
041: /**
042: * Constructs a new Base64 encoder that writes output to the given
043: * OutputStream.
044: *
045: * @param out the output stream
046: */
047: public Base64Encoder(OutputStream out) {
048: super (out);
049: }
050:
051: /**
052: * Writes the given byte to the output stream in an encoded form.
053: *
054: * @exception IOException if an I/O error occurs
055: */
056: public void write(int b) throws IOException {
057: // Take 24-bits from three octets, translate into four encoded chars
058: // Break lines at 76 chars
059: // If necessary, pad with 0 bits on the right at the end
060: // Use = signs as padding at the end to ensure encodedLength % 4 == 0
061:
062: // Remove the sign bit,
063: // thanks to Christian Schweingruber <chrigu@lorraine.ch>
064: if (b < 0) {
065: b += 256;
066: }
067:
068: // First byte use first six bits, save last two bits
069: if (charCount % 3 == 0) {
070: int lookup = b >> 2;
071: carryOver = b & 3; // last two bits
072: out.write(chars[lookup]);
073: }
074: // Second byte use previous two bits and first four new bits,
075: // save last four bits
076: else if (charCount % 3 == 1) {
077: int lookup = ((carryOver << 4) + (b >> 4)) & 63;
078: carryOver = b & 15; // last four bits
079: out.write(chars[lookup]);
080: }
081: // Third byte use previous four bits and first two new bits,
082: // then use last six new bits
083: else if (charCount % 3 == 2) {
084: int lookup = ((carryOver << 2) + (b >> 6)) & 63;
085: out.write(chars[lookup]);
086: lookup = b & 63; // last six bits
087: out.write(chars[lookup]);
088: carryOver = 0;
089: }
090: charCount++;
091:
092: // Add newline every 76 output chars (that's 57 input chars)
093: if (charCount % 57 == 0) {
094: out.write('\n');
095: }
096: }
097:
098: /**
099: * Writes the given byte array to the output stream in an
100: * encoded form.
101: *
102: * @param b the data to be written
103: * @param off the start offset of the data
104: * @param len the length of the data
105: * @exception IOException if an I/O error occurs
106: */
107: public void write(byte[] buf, int off, int len) throws IOException {
108: // This could of course be optimized
109: for (int i = 0; i < len; i++) {
110: write(buf[off + i]);
111: }
112: }
113:
114: /**
115: * Closes the stream, this MUST be called to ensure proper padding is
116: * written to the end of the output stream.
117: *
118: * @exception IOException if an I/O error occurs
119: */
120: public void close() throws IOException {
121: // Handle leftover bytes
122: if (charCount % 3 == 1) { // one leftover
123: int lookup = (carryOver << 4) & 63;
124: out.write(chars[lookup]);
125: out.write('=');
126: out.write('=');
127: } else if (charCount % 3 == 2) { // two leftovers
128: int lookup = (carryOver << 2) & 63;
129: out.write(chars[lookup]);
130: out.write('=');
131: }
132: super .close();
133: }
134:
135: /**
136: * Returns the encoded form of the given unencoded string. The encoder
137: * uses the ISO-8859-1 (Latin-1) encoding to convert the string to bytes.
138: * For greater control over the encoding, encode the string to bytes
139: * yourself and use encode(byte[]).
140: *
141: * @param unencoded the string to encode
142: * @return the encoded form of the unencoded string
143: */
144: public static String encode(String unencoded) {
145: byte[] bytes = null;
146: try {
147: bytes = unencoded.getBytes("8859_1");
148: } catch (UnsupportedEncodingException ignored) {
149: }
150: return encode(bytes);
151: }
152:
153: /**
154: * Returns the encoded form of the given unencoded string.
155: *
156: * @param unencoded the string to encode
157: * @return the encoded form of the unencoded string
158: */
159: public static String encode(byte[] bytes) {
160: ByteArrayOutputStream out = new ByteArrayOutputStream(
161: (int) (bytes.length * 1.37));
162: Base64Encoder encodedOut = new Base64Encoder(out);
163:
164: try {
165: encodedOut.write(bytes);
166: encodedOut.close();
167:
168: return out.toString("8859_1");
169: } catch (IOException ignored) {
170: return null;
171: }
172: }
173:
174: public static void main(String[] args) throws Exception {
175: if (args.length != 1) {
176: System.err
177: .println("Usage: java com.oreilly.servlet.Base64Encoder fileToEncode");
178: return;
179: }
180:
181: Base64Encoder encoder = null;
182: BufferedInputStream in = null;
183: try {
184: encoder = new Base64Encoder(System.out);
185: in = new BufferedInputStream(new FileInputStream(args[0]));
186:
187: byte[] buf = new byte[4 * 1024]; // 4K buffer
188: int bytesRead;
189: while ((bytesRead = in.read(buf)) != -1) {
190: encoder.write(buf, 0, bytesRead);
191: }
192: } finally {
193: if (in != null)
194: in.close();
195: if (encoder != null)
196: encoder.close();
197: }
198: }
199: }
|