KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > maverick > util > Base64


1 /*
2  * SSL-Explorer
3  *
4  * Copyright (C) 2003-2006 3SP LTD. All Rights Reserved
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2 of
9  * the License, or (at your option) any later version.
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public
16  * License along with this program; if not, write to the Free Software
17  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */

19             
20 package com.maverick.util;
21
22
23 /**
24  *
25  *
26  * @author $author$
27  */

28 public class Base64 {
29   /** */
30   public final static boolean ENCODE = true;
31
32   /** */
33   public final static boolean DECODE = false;
34   private final static int MAX_LINE_LENGTH = 76;
35   private final static byte EQUALS_SIGN = (byte) '=';
36   private final static byte NEW_LINE = (byte) '\n';
37   private final static byte[] ALPHABET = {
38       (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F',
39       (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L',
40       (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R',
41       (byte) 'S', (byte) 'T', (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X',
42       (byte) 'Y', (byte) 'Z', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd',
43       (byte) 'e', (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j',
44       (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p',
45       (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', (byte) 'v',
46       (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', (byte) '0', (byte) '1',
47       (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7',
48       (byte) '8', (byte) '9', (byte) '+', (byte) '/'
49   };
50   private final static byte[] DECODABET = {
51       -9, -9, -9, -9, -9, -9, -9, -9, -9, -5, -5, -9, -9, -5, -9, -9, -9, -9,
52       -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -5, -9, -9, -9,
53       -9, -9, -9, -9, -9, -9, -9,
54       // Decimal 33 - 42
55
62, -9, -9, -9,
56       // Decimal 44 - 46
57
63,
58       // Slash at decimal 47
59
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -9, -9, -9, -1, -9, -9, -9,
60       // Decimal 62 - 64
61
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
62       // Letters 'A' through 'N'
63
14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -9, -9, -9, -9, -9, -9,
64       // Decimal 91 - 96
65
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
66       // Letters 'a' through 'm'
67
39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -9, -9, -9, -9
68   };
69   private final static byte BAD_ENCODING = -9;
70
71   // Indicates error in encoding
72
private final static byte white_SPACE_ENC = -5;
73
74   // Indicates white space in encoding
75
private final static byte EQUALS_SIGN_ENC = -1;
76
77   // Indicates equals sign in encoding
78
private Base64() {
79   }
80
81   /**
82    *
83    *
84    * @param s
85    *
86    * @return
87    */

88   public static byte[] decode(String JavaDoc s) {
89     byte[] bytes = s.getBytes();
90
91     return decode(bytes, 0, bytes.length);
92   }
93
94   // end decode
95
public static byte[] decode(byte[] source, int off, int len) {
96     int len34 = (len * 3) / 4;
97     byte[] outBuff = new byte[len34];
98
99     // Upper limit on size of output
100
int outBuffPosn = 0;
101
102     byte[] b4 = new byte[4];
103     int b4Posn = 0;
104     int i = 0;
105     byte sbiCrop = 0;
106     byte sbiDecode = 0;
107
108     for (i = off; i < len; i++) {
109       sbiCrop = (byte) (source[i] & 0x7f);
110
111       // Only the low seven bits
112
sbiDecode = DECODABET[sbiCrop];
113
114       if (sbiDecode >= white_SPACE_ENC) {
115         // White space, Equals sign or better
116
if (sbiDecode >= EQUALS_SIGN_ENC) {
117           b4[b4Posn++] = sbiCrop;
118
119           if (b4Posn > 3) {
120             outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn);
121             b4Posn = 0;
122
123             // If that was the equals sign, break out of 'for' loop
124
if (sbiCrop == EQUALS_SIGN) {
125               break;
126             }
127           }
128
129           // end if: quartet built
130
}
131
132         // end if: equals sign or better
133
}
134       // end if: white space, equals sign or better
135
else {
136         System.err.println("Bad Base64 input character at " + i + ": "
137                            + source[i] + "(decimal)");
138
139         return null;
140       }
141
142       // end else:
143
}
144
145     // each input character
146
byte[] out = new byte[outBuffPosn];
147     System.arraycopy(outBuff, 0, out, 0, outBuffPosn);
148
149     return out;
150   }
151
152   // end decode
153
public static Object JavaDoc decodeToObject(String JavaDoc encodedObject) {
154     byte[] objBytes = decode(encodedObject);
155
156     java.io.ByteArrayInputStream JavaDoc bais = null;
157     java.io.ObjectInputStream JavaDoc ois = null;
158
159     try {
160       bais = new java.io.ByteArrayInputStream JavaDoc(objBytes);
161       ois = new java.io.ObjectInputStream JavaDoc(bais);
162
163       return ois.readObject();
164     }
165     // end try
166
catch (java.io.IOException JavaDoc e) {
167       return null;
168     }
169     // end catch
170
catch (java.lang.ClassNotFoundException JavaDoc e) {
171       return null;
172     }
173     // end catch
174
finally {
175       try {
176         bais.close();
177       }
178       catch (Exception JavaDoc e) {
179       }
180
181       try {
182         ois.close();
183       }
184       catch (Exception JavaDoc e) {
185       }
186     }
187
188     // end finally
189
}
190
191   // end decodeObject
192
public static String JavaDoc decodeToString(String JavaDoc s) {
193     return new String JavaDoc(decode(s));
194   }
195
196   // end decodeToString
197
public static String JavaDoc encodeBytes(byte[] source, boolean ignoreMaxLineLength) {
198     return encodeBytes(source, 0, source.length, ignoreMaxLineLength);
199   }
200
201   // end encodeBytes
202
public static String JavaDoc encodeBytes(byte[] source, int off, int len,
203                                    boolean ignoreMaxLineLength) {
204     int len43 = (len * 4) / 3;
205     byte[] outBuff = new byte[ (len43) + ( ( (len % 3) > 0) ? 4 : 0)
206         + (len43 / MAX_LINE_LENGTH)];
207
208     // New lines
209
int d = 0;
210     int e = 0;
211     int len2 = len - 2;
212     int lineLength = 0;
213
214     for (; d < len2; d += 3, e += 4) {
215       encode3to4(source, d + off, 3, outBuff, e);
216
217       lineLength += 4;
218
219       if (!ignoreMaxLineLength) {
220         if (lineLength == MAX_LINE_LENGTH) {
221           outBuff[e + 4] = NEW_LINE;
222           e++;
223           lineLength = 0;
224         }
225
226         // end if: end of line
227
}
228     }
229
230     // en dfor: each piece of array
231
if (d < len) {
232       encode3to4(source, d + off, len - d, outBuff, e);
233       e += 4;
234     }
235
236     // end if: some padding needed
237
return new String JavaDoc(outBuff, 0, e);
238   }
239
240   // end encodeBytes
241
public static String JavaDoc encodeObject(java.io.Serializable JavaDoc serializableObject) {
242     java.io.ByteArrayOutputStream JavaDoc baos = null;
243     java.io.OutputStream JavaDoc b64os = null;
244     java.io.ObjectOutputStream JavaDoc oos = null;
245
246     try {
247       baos = new java.io.ByteArrayOutputStream JavaDoc();
248       b64os = new Base64.OutputStream(baos, Base64.ENCODE);
249       oos = new java.io.ObjectOutputStream JavaDoc(b64os);
250
251       oos.writeObject(serializableObject);
252     }
253     // end try
254
catch (java.io.IOException JavaDoc e) {
255       return null;
256     }
257     // end catch
258
finally {
259       try {
260         oos.close();
261       }
262       catch (Exception JavaDoc e) {
263       }
264
265       try {
266         b64os.close();
267       }
268       catch (Exception JavaDoc e) {
269       }
270
271       try {
272         baos.close();
273       }
274       catch (Exception JavaDoc e) {
275       }
276     }
277
278     // end finally
279
return new String JavaDoc(baos.toByteArray());
280   }
281
282   // end encode
283
public static String JavaDoc encodeString(String JavaDoc s, boolean ignoreMaxLineLength) {
284     return encodeBytes(s.getBytes(), ignoreMaxLineLength);
285   }
286
287   // end encodeString
288
/* public static void main(String[] args) {
289       String s = "P2/56wAAAgoAAAAmZGwtbW9kcHtzaWdue2RzYS1uaXN0LXNoYTF9LGRoe3Bs"
290           +
291       "YWlufX0AAAAIM2Rlcy1jYmMAAAHIifTc7/X/swWj4OHVWX9RsUxWh4citAMwGzv6X9mUG6a"
292           +
293       "mh5/2f6IiQ3lOeHFd5J0EAOeGNuLqE/RWJ/fFaZAzD6YTr1GZ5hflMzvRu3jbgZoLRz2TaT"
294           +
295       "qeRs1yWrQoqANE2nBx6uDNrRahduqalLg2P/ezRCLGpqbw3HFgXmiZvzhd/rdEgZur7ZPnm"
296           +
297       "EK7t4Ldypk/7xcK192JTbBXLDSKOEAqfYQb9CzW8MgEXde0DpMRZ9Fgm0KWPfz4CCJ0F9dd"
298           +
299        "zcWl1nuGibL3klLKQANgecTurFlrxkBaHgxgl9nIvf24wH3nscvmD/uFOzacT/LzFaD03HFj"
300           +
301        "/QHCiTezxVyyuJ39d3e6BBegV26vEFoGbrZ2mMf08C2MBmLmZELYdBRJ4kLpT5EZkzR8L4rT"
302           +
303        "GxNiWkb4dGT42gHH41p2ad053lctyFWp/uQJnvJEiEm3BMURVY7k1S7zgv2FHgHE0LssXvBHx"
304           +
305        "n/wnft0ne2NOqEXfs/Y4I39Nd7eDIupSVy/ZFfMmNPIhzKyC5lFMkjIMxPXNk548ZoP9Tnga"
306           + "4NPhHNKtcMinVvO2HT6dnIKMNb/NuXooULHIMVISpslRzXiVlTcN9vL/jhJhn9S";
307       byte[] buf = Base64.decode(s);
308       System.out.println(new String(buf).toString());
309        s = "P2/56wAAAgIAAAAmZGwtbW9kcHtzaWdue2RzYS1uaXN0LXNoYTF9LGRoe3BsYWlufX0A"
310           +
311        "AAAEbm9uZQAAAcQAAAHAAAAAAAAABACwV9/fUska/ZHWa4YzXIPFJ4RbcFqPVV0vmyWkFekw"
312           +
313        "wKE1mA0GVDRq9X0HTjA2DZWcQ46suVP/8mLwpnjTKNiRdFvXWGkxEpavLp+bjPa/NXsEsjZL"
314           +
315        "aeO5iPZ11Xw5lx7uor8q/Ewwo9IcYOXzuOWN1EPCpdRv5OOaO3PCMq6QSQAAA/9j/IrSUDtf"
316           +
317        "BLBlzPHBrzboKjIMXv9O8CIRtSqnV7GV9wllgh3Cm+Eh+rd5CB698JGQD9tMdBn4s8bj/BDL"
318           +
319        "4qsxbQbAsZOIin6fqDKNLDxFo357eXM06I5569PgC6cuBoJXOyQTg+sLrjT8/b3/1N4TjdZN"
320           +
321        "JiKiSiuOzkn03tNSbgAAAKDJhI2ZNNvzOXhp+VFuoY//D9GvHwAAA/9NkAROm4wF7NCPsBXd"
322           +
323        "/+QfNV3NM/FSpOonZZDg2AVnCCGdLOXCWEj60EVHWEf5FbOjJ1KynbbdZA6q5JtVDIYuU9wH"
324           +
325        "BCsT5iCexGD5j2HYNcUXT4VG5a6qzqloR2JizlZOcjiEM2j0/hydFUei0VYmJNY5L//AprO6"
326           + "1UJL2OGFEQAAAJ0Ts+KlcAYmJjJWODOG3mYuiTgv7A==";
327       buf = Base64.decode(s);
328       System.out.println(new String(buf).toString());
329       buf = Base64.decode(
330           "P2/56wAAAi4AAAA3aWYtbW9kbntzaWdue3JzYS1wa2NzMS1zaGExfSxlbmNyeXB0e3JzYS1wa2NzMXYyLW9hZXB9fQAAAARub25lAAAB3wAAAdsAAAARAQABAAAD/iJ48YNIqLobasqkyRAD6Ejzhe0bK0Nd12iq0X9xG7M5xyVJns5SH3oAPwsa/V63omsQnm/ERG5lCnFGymTSCTpz0jGYLAh81S4XGbZEJRltP75LiM4J1OIfQkF7Zxd/mYFAYpu50fOLTrk+EwOCyQJK63uXzxQHCU1JKzt61m05AAAEALhvA6F1Ffhf/HLPKe3mp/CdTYQyioHzdL2ur6jyvh+b5wb8WuiaL+xu08vA7/Q763M/TXLX3jMWKOfV3HFn656hBCjnePwXp+uJNIQ4+oxg5H7nr8yo2Tc3Umt9fzgajoLDSd488iozmlSgKeRoVy7hKAGuveGtFqqruNAYArNfAAACALXcpb2stcqNdyTGUPIK/uUBkEeEJGgomqFPZbkMNHqZqEPLa7cJdHIl6wiol3ziQKvvUm/8ya4y7tR9Mzay/cIAAAIAwU2/rquz6oQ1GVJVRsO47Ibes2Hcl8tZRC9cBDy5vIPhzPhsD3pxxXnc1gEUybWqkuO6q1XilE/qN/eAKFSDuQAAAgD0QMX768Ucuv2Eu/ZVkebKBBV7jo4seZyd+hKloFotU4mReU7kNq+oYG19pL07n1TN4SodVoykXPSLBowCKCvX");
331       System.out.println(new String(buf).toString());
332       buf = Base64.decode(
333           "P2/56wAAAjsAAAA3aWYtbW9kbntzaWdue3JzYS1wa2NzMS1zaGExfSxlbmNyeXB0e3JzYS1wa2NzMXYyLW9hZXB9fQAAAAgzZGVzLWNiYwAAAegYJSJacx5dZo5rvtyJEp5qFyBXDOkcGH/H4/dJuny1cWnP5eXOaYt1hwc6ZEUIq4bUISGuXSzmRb+mpXZdkAPPt2RLhy66FnwnERnbItyWsNHrMxT5/oug/TW1l+rh0m/46edQhkla+qpgt3ZCJfBRzwihKAAeQJIt18e7XmvVT5g14Xu5fulXPfKT/cPu6Ox1pwRrOTv2ooM8alM2+K+5uCaP9C3qhEhFcyZOsKoigJt8oIZJD7TBrb2adVfzjyNWXZLw5Lq+liWmGTePvf9Mkx+MgFAyIOT4gV391+Rit8ZjSQaJ5jtsSaqw/MgqtTCWz6aXAaLnxP579a+tVubfVQrGLAa6ztGjI/0DmzEH+OvOLfXljeaEPKXhOxTf2O7Pwn8MDBStJHPXPLZZnsoUyTCajnzxw/ohqxOtgE9nqqO1QFVF6Cd74yZlhQSScRKkBcUlqcenxtruEOvvZXgAc8T5UtfvF8AooI22zltyKZDFJx3vJD6TEoFQSq4zu8H4Eipr42HPpUvIFuVAJFlZepI/RVirsU6sDjh8do0vj9ZGdhdBaD8kR7lrPHAJkmROHljJhEI97YWUJZNXS9i63gVvplsi9/x6uEWjn8eNu08IXID82X+LbvEdmTWOhuaSIqyNjyVe7g==");
334       System.out.println(new String(buf).toString());
335     }*/

336
337   /*
338    * ******** D E C O D I N G M E T H O D S ********
339    */

340   private static byte[] decode4to3(byte[] fourBytes) {
341     byte[] outBuff1 = new byte[3];
342     int count = decode4to3(fourBytes, 0, outBuff1, 0);
343     byte[] outBuff2 = new byte[count];
344
345     for (int i = 0; i < count; i++) {
346       outBuff2[i] = outBuff1[i];
347     }
348
349     return outBuff2;
350   }
351
352   private static int decode4to3(byte[] source, int srcOffset,
353                                 byte[] destination, int destOffset) {
354     // Example: Dk==
355
if (source[srcOffset + 2] == EQUALS_SIGN) {
356       int outBuff = ( (DECODABET[source[srcOffset]] << 24) >>> 6)
357           | ( (DECODABET[source[srcOffset + 1]] << 24) >>> 12);
358
359       destination[destOffset] = (byte) (outBuff >>> 16);
360
361       return 1;
362     }
363     // Example: DkL=
364
else if (source[srcOffset + 3] == EQUALS_SIGN) {
365       int outBuff = ( (DECODABET[source[srcOffset]] << 24) >>> 6)
366           | ( (DECODABET[source[srcOffset + 1]] << 24) >>> 12)
367           | ( (DECODABET[source[srcOffset + 2]] << 24) >>> 18);
368
369       destination[destOffset] = (byte) (outBuff >>> 16);
370       destination[destOffset + 1] = (byte) (outBuff >>> 8);
371
372       return 2;
373     }
374     // Example: DkLE
375
else {
376       int outBuff = ( (DECODABET[source[srcOffset]] << 24) >>> 6)
377           | ( (DECODABET[source[srcOffset + 1]] << 24) >>> 12)
378           | ( (DECODABET[source[srcOffset + 2]] << 24) >>> 18)
379           | ( (DECODABET[source[srcOffset + 3]] << 24) >>> 24);
380
381       destination[destOffset] = (byte) (outBuff >> 16);
382       destination[destOffset + 1] = (byte) (outBuff >> 8);
383       destination[destOffset + 2] = (byte) (outBuff);
384
385       return 3;
386     }
387   }
388
389   // end decodeToBytes
390

391   /*
392    * ******** E N C O D I N G M E T H O D S ********
393    */

394   private static byte[] encode3to4(byte[] threeBytes) {
395     return encode3to4(threeBytes, 3);
396   }
397
398   // end encodeToBytes
399
private static byte[] encode3to4(byte[] threeBytes, int numSigBytes) {
400     byte[] dest = new byte[4];
401     encode3to4(threeBytes, 0, numSigBytes, dest, 0);
402
403     return dest;
404   }
405
406   private static byte[] encode3to4(byte[] source, int srcOffset,
407                                    int numSigBytes, byte[] destination,
408                                    int destOffset) {
409     // 1 2 3
410
// 01234567890123456789012345678901 Bit position
411
// --------000000001111111122222222 Array position from threeBytes
412
// --------| || || || | Six bit groups to index ALPHABET
413
// >>18 >>12 >> 6 >> 0 Right shift necessary
414
// 0x3f 0x3f 0x3f Additional AND
415
// Create buffer with zero-padding if there are only one or two
416
// significant bytes passed in the array.
417
// We have to shift left 24 in order to flush out the 1's that appear
418
// when Java treats a value as negative that is cast from a byte to an int.
419
int inBuff = ( (numSigBytes > 0) ? ( (source[srcOffset] << 24) >>> 8) : 0)
420         | ( (numSigBytes > 1) ? ( (source[srcOffset + 1] << 24) >>> 16) : 0)
421         | ( (numSigBytes > 2) ? ( (source[srcOffset + 2] << 24) >>> 24) : 0);
422
423     switch (numSigBytes) {
424       case 3:
425         destination[destOffset] = ALPHABET[ (inBuff >>> 18)];
426         destination[destOffset + 1] = ALPHABET[ (inBuff >>> 12) & 0x3f];
427         destination[destOffset + 2] = ALPHABET[ (inBuff >>> 6) & 0x3f];
428         destination[destOffset + 3] = ALPHABET[ (inBuff) & 0x3f];
429
430         return destination;
431
432       case 2:
433         destination[destOffset] = ALPHABET[ (inBuff >>> 18)];
434         destination[destOffset + 1] = ALPHABET[ (inBuff >>> 12) & 0x3f];
435         destination[destOffset + 2] = ALPHABET[ (inBuff >>> 6) & 0x3f];
436         destination[destOffset + 3] = EQUALS_SIGN;
437
438         return destination;
439
440       case 1:
441         destination[destOffset] = ALPHABET[ (inBuff >>> 18)];
442         destination[destOffset + 1] = ALPHABET[ (inBuff >>> 12) & 0x3f];
443         destination[destOffset + 2] = EQUALS_SIGN;
444         destination[destOffset + 3] = EQUALS_SIGN;
445
446         return destination;
447
448       default:
449         return destination;
450     }
451
452     // end switch
453
}
454
455   // end encode3to4
456

457   /*
458    * ******** I N N E R C L A S S I N P U T S T R E A M ********
459    */

460   public static class InputStream
461       extends java.io.FilterInputStream JavaDoc {
462     private byte[] buffer;
463
464     // Small buffer holding converted data
465
private boolean encode;
466
467     // Encoding or decoding
468
private int bufferLength;
469
470     // Length of buffer (3 or 4)
471
private int numSigBytes;
472
473     // Number of meaningful bytes in the buffer
474
private int position;
475
476     // Current position in the buffer
477
public InputStream(java.io.InputStream JavaDoc in) {
478       this(in, Base64.DECODE);
479     }
480
481     // end constructor
482
public InputStream(java.io.InputStream JavaDoc in, boolean encode) {
483       super(in);
484       this.encode = encode;
485       this.bufferLength = encode ? 4 : 3;
486       this.buffer = new byte[bufferLength];
487       this.position = -1;
488     }
489
490     // end constructor
491
public int read() throws java.io.IOException JavaDoc {
492       // Do we need to get data?
493
if (position < 0) {
494         if (encode) {
495           byte[] b3 = new byte[3];
496           numSigBytes = 0;
497
498           for (int i = 0; i < 3; i++) {
499             try {
500               int b = in.read();
501
502               // If end of stream, b is -1.
503
if (b >= 0) {
504                 b3[i] = (byte) b;
505                 numSigBytes++;
506               }
507
508               // end if: not end of stream
509
}
510             // end try: read
511
catch (java.io.IOException JavaDoc e) {
512               // Only a problem if we got no data at all.
513
if (i == 0) {
514                 throw e;
515               }
516             }
517
518             // end catch
519
}
520
521           // end for: each needed input byte
522
if (numSigBytes > 0) {
523             encode3to4(b3, 0, numSigBytes, buffer, 0);
524             position = 0;
525           }
526
527           // end if: got data
528
}
529         // end if: encoding
530
// Else decoding
531
else {
532           byte[] b4 = new byte[4];
533           int i = 0;
534
535           for (i = 0; i < 4; i++) {
536             int b = 0;
537
538             do {
539               b = in.read();
540             }
541             while ( (b >= 0)
542                    && (DECODABET[b & 0x7f] < white_SPACE_ENC));
543
544             if (b < 0) {
545               break;
546
547               // Reads a -1 if end of stream
548
}
549
550             b4[i] = (byte) b;
551           }
552
553           // end for: each needed input byte
554
if (i == 4) {
555             numSigBytes = decode4to3(b4, 0, buffer, 0);
556             position = 0;
557           }
558
559           // end if: got four characters
560
}
561
562         // end else: decode
563
}
564
565       // end else: get data
566
// Got data?
567
if (position >= 0) {
568         // End of relevant data?
569
if (!encode && (position >= numSigBytes)) {
570           return -1;
571         }
572
573         int b = buffer[position++];
574
575         if (position >= bufferLength) {
576           position = -1;
577         }
578
579         return b;
580       }
581       // end if: position >= 0
582
// Else error
583
else {
584         return -1;
585       }
586     }
587
588     // end read
589
public int read(byte[] dest, int off, int len) throws java.io.IOException JavaDoc {
590       int i;
591       int b;
592
593       for (i = 0; i < len; i++) {
594         b = read();
595
596         if (b < 0) {
597           return -1;
598         }
599
600         dest[off + i] = (byte) b;
601       }
602
603       // end for: each byte read
604
return i;
605     }
606
607     // end read
608
}
609
610   // end inner class InputStream
611

612   /*
613    * ******** I N N E R C L A S S O U T P U T S T R E A M ********
614    */

615   public static class OutputStream
616       extends java.io.FilterOutputStream JavaDoc {
617     private byte[] buffer;
618     private boolean encode;
619     private int bufferLength;
620     private int lineLength;
621     private int position;
622
623     public OutputStream(java.io.OutputStream JavaDoc out) {
624       this(out, Base64.ENCODE);
625     }
626
627     // end constructor
628
public OutputStream(java.io.OutputStream JavaDoc out, boolean encode) {
629       super(out);
630       this.encode = encode;
631       this.bufferLength = encode ? 3 : 4;
632       this.buffer = new byte[bufferLength];
633       this.position = 0;
634       this.lineLength = 0;
635     }
636
637     // end constructor
638
public void close() throws java.io.IOException JavaDoc {
639       this.flush();
640
641       super.close();
642       out.close();
643
644       buffer = null;
645       out = null;
646     }
647
648     // end close
649
public void flush() throws java.io.IOException JavaDoc {
650       if (position > 0) {
651         if (encode) {
652           out.write(Base64.encode3to4(buffer, position));
653         }
654         // end if: encoding
655
else {
656           throw new java.io.IOException JavaDoc(
657               "Base64 input not properly padded.");
658         }
659
660         // end else: decoding
661
}
662
663       // end if: buffer partially full
664
super.flush();
665       out.flush();
666     }
667
668     // end flush
669
public void write(int theByte) throws java.io.IOException JavaDoc {
670       buffer[position++] = (byte) theByte;
671
672       if (position >= bufferLength) {
673         if (encode) {
674           out.write(Base64.encode3to4(buffer, bufferLength));
675
676           lineLength += 4;
677
678           if (lineLength >= MAX_LINE_LENGTH) {
679             out.write(NEW_LINE);
680             lineLength = 0;
681           }
682
683           // end if: end o fline
684
}
685         // end if: encoding
686
else {
687           out.write(Base64.decode4to3(buffer));
688         }
689
690         position = 0;
691       }
692
693       // end if: convert and flush
694
}
695
696     // end write
697
public void write(byte[] theBytes, int off, int len) throws java.io.
698
JavaDoc        IOException {
699       for (int i = 0; i < len; i++) {
700         write(theBytes[off + i]);
701       }
702
703       // end for: each byte written
704
}
705
706     // end write
707
}
708
709   // end inner class OutputStream
710
}
711 // end class Base64
712
Popular Tags