Commit | Line | Data |
---|---|---|
3f5430db MM |
1 | package net.mattmccutchen.measurements; |
2 | ||
3 | /** | |
4 | * <p>Encodes and decodes to and from Base64 notation.</p> | |
5 | * <p>Homepage: <a href="http://iharder.net/base64">http://iharder.net/base64</a>.</p> | |
6 | * | |
7 | * <p> | |
8 | * Change Log: | |
9 | * </p> | |
10 | * <ul> | |
11 | * <li>v2.2.1 - Fixed bug using URL_SAFE and ORDERED encodings. Fixed bug | |
12 | * when using very small files (~< 40 bytes).</li> | |
13 | * <li>v2.2 - Added some helper methods for encoding/decoding directly from | |
14 | * one file to the next. Also added a main() method to support command line | |
15 | * encoding/decoding from one file to the next. Also added these Base64 dialects: | |
16 | * <ol> | |
17 | * <li>The default is RFC3548 format.</li> | |
18 | * <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.URLSAFE_FORMAT) generates | |
19 | * URL and file name friendly format as described in Section 4 of RFC3548. | |
20 | * http://www.faqs.org/rfcs/rfc3548.html</li> | |
21 | * <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.ORDERED_FORMAT) generates | |
22 | * URL and file name friendly format that preserves lexical ordering as described | |
23 | * in http://www.faqs.org/qa/rfcc-1940.html</li> | |
24 | * </ol> | |
25 | * Special thanks to Jim Kellerman at <a href="http://www.powerset.com/">http://www.powerset.com/</a> | |
26 | * for contributing the new Base64 dialects. | |
27 | * </li> | |
28 | * | |
29 | * <li>v2.1 - Cleaned up javadoc comments and unused variables and methods. Added | |
30 | * some convenience methods for reading and writing to and from files.</li> | |
31 | * <li>v2.0.2 - Now specifies UTF-8 encoding in places where the code fails on systems | |
32 | * with other encodings (like EBCDIC).</li> | |
33 | * <li>v2.0.1 - Fixed an error when decoding a single byte, that is, when the | |
34 | * encoded data was a single byte.</li> | |
35 | * <li>v2.0 - I got rid of methods that used booleans to set options. | |
36 | * Now everything is more consolidated and cleaner. The code now detects | |
37 | * when data that's being decoded is gzip-compressed and will decompress it | |
38 | * automatically. Generally things are cleaner. You'll probably have to | |
39 | * change some method calls that you were making to support the new | |
40 | * options format (<tt>int</tt>s that you "OR" together).</li> | |
41 | * <li>v1.5.1 - Fixed bug when decompressing and decoding to a | |
42 | * byte[] using <tt>decode( String s, boolean gzipCompressed )</tt>. | |
43 | * Added the ability to "suspend" encoding in the Output Stream so | |
44 | * you can turn on and off the encoding if you need to embed base64 | |
45 | * data in an otherwise "normal" stream (like an XML file).</li> | |
46 | * <li>v1.5 - Output stream pases on flush() command but doesn't do anything itself. | |
47 | * This helps when using GZIP streams. | |
48 | * Added the ability to GZip-compress objects before encoding them.</li> | |
49 | * <li>v1.4 - Added helper methods to read/write files.</li> | |
50 | * <li>v1.3.6 - Fixed OutputStream.flush() so that 'position' is reset.</li> | |
51 | * <li>v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in input stream | |
52 | * where last buffer being read, if not completely full, was not returned.</li> | |
53 | * <li>v1.3.4 - Fixed when "improperly padded stream" error was thrown at the wrong time.</li> | |
54 | * <li>v1.3.3 - Fixed I/O streams which were totally messed up.</li> | |
55 | * </ul> | |
56 | * | |
57 | * <p> | |
58 | * I am placing this code in the Public Domain. Do with it as you will. | |
59 | * This software comes with no guarantees or warranties but with | |
60 | * plenty of well-wishing instead! | |
61 | * Please visit <a href="http://iharder.net/base64">http://iharder.net/base64</a> | |
62 | * periodically to check for updates or to contribute improvements. | |
63 | * </p> | |
64 | * | |
65 | * @author Robert Harder | |
66 | * @author rob@iharder.net | |
67 | * @version 2.2.1 | |
68 | */ | |
69 | public class Base64 | |
70 | { | |
71 | ||
72 | /* ******** P U B L I C F I E L D S ******** */ | |
73 | ||
74 | ||
75 | /** No options specified. Value is zero. */ | |
76 | public final static int NO_OPTIONS = 0; | |
77 | ||
78 | /** Specify encoding. */ | |
79 | public final static int ENCODE = 1; | |
80 | ||
81 | ||
82 | /** Specify decoding. */ | |
83 | public final static int DECODE = 0; | |
84 | ||
85 | ||
86 | /** Specify that data should be gzip-compressed. */ | |
87 | public final static int GZIP = 2; | |
88 | ||
89 | ||
90 | /** Don't break lines when encoding (violates strict Base64 specification) */ | |
91 | public final static int DONT_BREAK_LINES = 8; | |
92 | ||
93 | /** | |
94 | * Encode using Base64-like encoding that is URL- and Filename-safe as described | |
95 | * in Section 4 of RFC3548: | |
96 | * <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>. | |
97 | * It is important to note that data encoded this way is <em>not</em> officially valid Base64, | |
98 | * or at the very least should not be called Base64 without also specifying that is | |
99 | * was encoded using the URL- and Filename-safe dialect. | |
100 | */ | |
101 | public final static int URL_SAFE = 16; | |
102 | ||
103 | ||
104 | /** | |
105 | * Encode using the special "ordered" dialect of Base64 described here: | |
106 | * <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>. | |
107 | */ | |
108 | public final static int ORDERED = 32; | |
109 | ||
110 | ||
111 | /** | |
112 | * In {@link #decode(String, int)}, do not automatically ungzip data that | |
113 | * has the gzip magic number. | |
114 | * | |
115 | * Modification by Matt! | |
116 | */ | |
117 | public final static int NO_GZIP_MAGIC = 64; | |
118 | ||
119 | /* ******** P R I V A T E F I E L D S ******** */ | |
120 | ||
121 | ||
122 | /** Maximum line length (76) of Base64 output. */ | |
123 | private final static int MAX_LINE_LENGTH = 76; | |
124 | ||
125 | ||
126 | /** The equals sign (=) as a byte. */ | |
127 | private final static byte EQUALS_SIGN = (byte)'='; | |
128 | ||
129 | ||
130 | /** The new line character (\n) as a byte. */ | |
131 | private final static byte NEW_LINE = (byte)'\n'; | |
132 | ||
133 | ||
134 | /** Preferred encoding. */ | |
135 | private final static String PREFERRED_ENCODING = "UTF-8"; | |
136 | ||
137 | ||
138 | // I think I end up not using the BAD_ENCODING indicator. | |
139 | //private final static byte BAD_ENCODING = -9; // Indicates error in encoding | |
140 | private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding | |
141 | private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding | |
142 | ||
143 | ||
144 | /* ******** S T A N D A R D B A S E 6 4 A L P H A B E T ******** */ | |
145 | ||
146 | /** The 64 valid Base64 values. */ | |
147 | //private final static byte[] ALPHABET; | |
148 | /* Host platform me be something funny like EBCDIC, so we hardcode these values. */ | |
149 | private final static byte[] _STANDARD_ALPHABET = | |
150 | { | |
151 | (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', | |
152 | (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', | |
153 | (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', | |
154 | (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', | |
155 | (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', | |
156 | (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', | |
157 | (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', | |
158 | (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z', | |
159 | (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', | |
160 | (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/' | |
161 | }; | |
162 | ||
163 | ||
164 | /** | |
165 | * Translates a Base64 value to either its 6-bit reconstruction value | |
166 | * or a negative number indicating some other meaning. | |
167 | **/ | |
168 | private final static byte[] _STANDARD_DECODABET = | |
169 | { | |
170 | -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 | |
171 | -5,-5, // Whitespace: Tab and Linefeed | |
172 | -9,-9, // Decimal 11 - 12 | |
173 | -5, // Whitespace: Carriage Return | |
174 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 | |
175 | -9,-9,-9,-9,-9, // Decimal 27 - 31 | |
176 | -5, // Whitespace: Space | |
177 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 | |
178 | 62, // Plus sign at decimal 43 | |
179 | -9,-9,-9, // Decimal 44 - 46 | |
180 | 63, // Slash at decimal 47 | |
181 | 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine | |
182 | -9,-9,-9, // Decimal 58 - 60 | |
183 | -1, // Equals sign at decimal 61 | |
184 | -9,-9,-9, // Decimal 62 - 64 | |
185 | 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N' | |
186 | 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z' | |
187 | -9,-9,-9,-9,-9,-9, // Decimal 91 - 96 | |
188 | 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm' | |
189 | 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z' | |
190 | -9,-9,-9,-9 // Decimal 123 - 126 | |
191 | /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139 | |
192 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 | |
193 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 | |
194 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 | |
195 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 | |
196 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 | |
197 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 | |
198 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 | |
199 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 | |
200 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */ | |
201 | }; | |
202 | ||
203 | ||
204 | /* ******** U R L S A F E B A S E 6 4 A L P H A B E T ******** */ | |
205 | ||
206 | /** | |
207 | * Used in the URL- and Filename-safe dialect described in Section 4 of RFC3548: | |
208 | * <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>. | |
209 | * Notice that the last two bytes become "hyphen" and "underscore" instead of "plus" and "slash." | |
210 | */ | |
211 | private final static byte[] _URL_SAFE_ALPHABET = | |
212 | { | |
213 | (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', | |
214 | (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', | |
215 | (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', | |
216 | (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', | |
217 | (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', | |
218 | (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', | |
219 | (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', | |
220 | (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z', | |
221 | (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', | |
222 | (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'-', (byte)'_' | |
223 | }; | |
224 | ||
225 | /** | |
226 | * Used in decoding URL- and Filename-safe dialects of Base64. | |
227 | */ | |
228 | private final static byte[] _URL_SAFE_DECODABET = | |
229 | { | |
230 | -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 | |
231 | -5,-5, // Whitespace: Tab and Linefeed | |
232 | -9,-9, // Decimal 11 - 12 | |
233 | -5, // Whitespace: Carriage Return | |
234 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 | |
235 | -9,-9,-9,-9,-9, // Decimal 27 - 31 | |
236 | -5, // Whitespace: Space | |
237 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 | |
238 | -9, // Plus sign at decimal 43 | |
239 | -9, // Decimal 44 | |
240 | 62, // Minus sign at decimal 45 | |
241 | -9, // Decimal 46 | |
242 | -9, // Slash at decimal 47 | |
243 | 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine | |
244 | -9,-9,-9, // Decimal 58 - 60 | |
245 | -1, // Equals sign at decimal 61 | |
246 | -9,-9,-9, // Decimal 62 - 64 | |
247 | 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N' | |
248 | 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z' | |
249 | -9,-9,-9,-9, // Decimal 91 - 94 | |
250 | 63, // Underscore at decimal 95 | |
251 | -9, // Decimal 96 | |
252 | 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm' | |
253 | 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z' | |
254 | -9,-9,-9,-9 // Decimal 123 - 126 | |
255 | /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139 | |
256 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 | |
257 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 | |
258 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 | |
259 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 | |
260 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 | |
261 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 | |
262 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 | |
263 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 | |
264 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */ | |
265 | }; | |
266 | ||
267 | ||
268 | ||
269 | /* ******** O R D E R E D B A S E 6 4 A L P H A B E T ******** */ | |
270 | ||
271 | /** | |
272 | * I don't get the point of this technique, but it is described here: | |
273 | * <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>. | |
274 | */ | |
275 | private final static byte[] _ORDERED_ALPHABET = | |
276 | { | |
277 | (byte)'-', | |
278 | (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', | |
279 | (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', | |
280 | (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', | |
281 | (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', | |
282 | (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', | |
283 | (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', | |
284 | (byte)'_', | |
285 | (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', | |
286 | (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', | |
287 | (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', | |
288 | (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z' | |
289 | }; | |
290 | ||
291 | /** | |
292 | * Used in decoding the "ordered" dialect of Base64. | |
293 | */ | |
294 | private final static byte[] _ORDERED_DECODABET = | |
295 | { | |
296 | -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 | |
297 | -5,-5, // Whitespace: Tab and Linefeed | |
298 | -9,-9, // Decimal 11 - 12 | |
299 | -5, // Whitespace: Carriage Return | |
300 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 | |
301 | -9,-9,-9,-9,-9, // Decimal 27 - 31 | |
302 | -5, // Whitespace: Space | |
303 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 | |
304 | -9, // Plus sign at decimal 43 | |
305 | -9, // Decimal 44 | |
306 | 0, // Minus sign at decimal 45 | |
307 | -9, // Decimal 46 | |
308 | -9, // Slash at decimal 47 | |
309 | 1,2,3,4,5,6,7,8,9,10, // Numbers zero through nine | |
310 | -9,-9,-9, // Decimal 58 - 60 | |
311 | -1, // Equals sign at decimal 61 | |
312 | -9,-9,-9, // Decimal 62 - 64 | |
313 | 11,12,13,14,15,16,17,18,19,20,21,22,23, // Letters 'A' through 'M' | |
314 | 24,25,26,27,28,29,30,31,32,33,34,35,36, // Letters 'N' through 'Z' | |
315 | -9,-9,-9,-9, // Decimal 91 - 94 | |
316 | 37, // Underscore at decimal 95 | |
317 | -9, // Decimal 96 | |
318 | 38,39,40,41,42,43,44,45,46,47,48,49,50, // Letters 'a' through 'm' | |
319 | 51,52,53,54,55,56,57,58,59,60,61,62,63, // Letters 'n' through 'z' | |
320 | -9,-9,-9,-9 // Decimal 123 - 126 | |
321 | /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139 | |
322 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 | |
323 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 | |
324 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 | |
325 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 | |
326 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 | |
327 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 | |
328 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 | |
329 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 | |
330 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */ | |
331 | }; | |
332 | ||
333 | ||
334 | /* ******** D E T E R M I N E W H I C H A L H A B E T ******** */ | |
335 | ||
336 | ||
337 | /** | |
338 | * Returns one of the _SOMETHING_ALPHABET byte arrays depending on | |
339 | * the options specified. | |
340 | * It's possible, though silly, to specify ORDERED and URLSAFE | |
341 | * in which case one of them will be picked, though there is | |
342 | * no guarantee as to which one will be picked. | |
343 | */ | |
344 | private final static byte[] getAlphabet( int options ) | |
345 | { | |
346 | if( (options & URL_SAFE) == URL_SAFE ) return _URL_SAFE_ALPHABET; | |
347 | else if( (options & ORDERED) == ORDERED ) return _ORDERED_ALPHABET; | |
348 | else return _STANDARD_ALPHABET; | |
349 | ||
350 | } // end getAlphabet | |
351 | ||
352 | ||
353 | /** | |
354 | * Returns one of the _SOMETHING_DECODABET byte arrays depending on | |
355 | * the options specified. | |
356 | * It's possible, though silly, to specify ORDERED and URL_SAFE | |
357 | * in which case one of them will be picked, though there is | |
358 | * no guarantee as to which one will be picked. | |
359 | */ | |
360 | private final static byte[] getDecodabet( int options ) | |
361 | { | |
362 | if( (options & URL_SAFE) == URL_SAFE ) return _URL_SAFE_DECODABET; | |
363 | else if( (options & ORDERED) == ORDERED ) return _ORDERED_DECODABET; | |
364 | else return _STANDARD_DECODABET; | |
365 | ||
366 | } // end getAlphabet | |
367 | ||
368 | ||
369 | ||
370 | /** Defeats instantiation. */ | |
371 | private Base64(){} | |
372 | ||
373 | ||
374 | /** | |
375 | * Encodes or decodes two files from the command line; | |
376 | * <strong>feel free to delete this method (in fact you probably should) | |
377 | * if you're embedding this code into a larger program.</strong> | |
378 | */ | |
379 | public final static void main( String[] args ) | |
380 | { | |
381 | if( args.length < 3 ){ | |
382 | usage("Not enough arguments."); | |
383 | } // end if: args.length < 3 | |
384 | else { | |
385 | String flag = args[0]; | |
386 | String infile = args[1]; | |
387 | String outfile = args[2]; | |
388 | if( flag.equals( "-e" ) ){ | |
389 | Base64.encodeFileToFile( infile, outfile ); | |
390 | } // end if: encode | |
391 | else if( flag.equals( "-d" ) ) { | |
392 | Base64.decodeFileToFile( infile, outfile ); | |
393 | } // end else if: decode | |
394 | else { | |
395 | usage( "Unknown flag: " + flag ); | |
396 | } // end else | |
397 | } // end else | |
398 | } // end main | |
399 | ||
400 | /** | |
401 | * Prints command line usage. | |
402 | * | |
403 | * @param msg A message to include with usage info. | |
404 | */ | |
405 | private final static void usage( String msg ) | |
406 | { | |
407 | System.err.println( msg ); | |
408 | System.err.println( "Usage: java Base64 -e|-d inputfile outputfile" ); | |
409 | } // end usage | |
410 | ||
411 | ||
412 | /* ******** E N C O D I N G M E T H O D S ******** */ | |
413 | ||
414 | ||
415 | /** | |
416 | * Encodes up to the first three bytes of array <var>threeBytes</var> | |
417 | * and returns a four-byte array in Base64 notation. | |
418 | * The actual number of significant bytes in your array is | |
419 | * given by <var>numSigBytes</var>. | |
420 | * The array <var>threeBytes</var> needs only be as big as | |
421 | * <var>numSigBytes</var>. | |
422 | * Code can reuse a byte array by passing a four-byte array as <var>b4</var>. | |
423 | * | |
424 | * @param b4 A reusable byte array to reduce array instantiation | |
425 | * @param threeBytes the array to convert | |
426 | * @param numSigBytes the number of significant bytes in your array | |
427 | * @return four byte array in Base64 notation. | |
428 | * @since 1.5.1 | |
429 | */ | |
430 | private static byte[] encode3to4( byte[] b4, byte[] threeBytes, int numSigBytes, int options ) | |
431 | { | |
432 | encode3to4( threeBytes, 0, numSigBytes, b4, 0, options ); | |
433 | return b4; | |
434 | } // end encode3to4 | |
435 | ||
436 | ||
437 | /** | |
438 | * <p>Encodes up to three bytes of the array <var>source</var> | |
439 | * and writes the resulting four Base64 bytes to <var>destination</var>. | |
440 | * The source and destination arrays can be manipulated | |
441 | * anywhere along their length by specifying | |
442 | * <var>srcOffset</var> and <var>destOffset</var>. | |
443 | * This method does not check to make sure your arrays | |
444 | * are large enough to accomodate <var>srcOffset</var> + 3 for | |
445 | * the <var>source</var> array or <var>destOffset</var> + 4 for | |
446 | * the <var>destination</var> array. | |
447 | * The actual number of significant bytes in your array is | |
448 | * given by <var>numSigBytes</var>.</p> | |
449 | * <p>This is the lowest level of the encoding methods with | |
450 | * all possible parameters.</p> | |
451 | * | |
452 | * @param source the array to convert | |
453 | * @param srcOffset the index where conversion begins | |
454 | * @param numSigBytes the number of significant bytes in your array | |
455 | * @param destination the array to hold the conversion | |
456 | * @param destOffset the index where output will be put | |
457 | * @return the <var>destination</var> array | |
458 | * @since 1.3 | |
459 | */ | |
460 | private static byte[] encode3to4( | |
461 | byte[] source, int srcOffset, int numSigBytes, | |
462 | byte[] destination, int destOffset, int options ) | |
463 | { | |
464 | byte[] ALPHABET = getAlphabet( options ); | |
465 | ||
466 | // 1 2 3 | |
467 | // 01234567890123456789012345678901 Bit position | |
468 | // --------000000001111111122222222 Array position from threeBytes | |
469 | // --------| || || || | Six bit groups to index ALPHABET | |
470 | // >>18 >>12 >> 6 >> 0 Right shift necessary | |
471 | // 0x3f 0x3f 0x3f Additional AND | |
472 | ||
473 | // Create buffer with zero-padding if there are only one or two | |
474 | // significant bytes passed in the array. | |
475 | // We have to shift left 24 in order to flush out the 1's that appear | |
476 | // when Java treats a value as negative that is cast from a byte to an int. | |
477 | int inBuff = ( numSigBytes > 0 ? ((source[ srcOffset ] << 24) >>> 8) : 0 ) | |
478 | | ( numSigBytes > 1 ? ((source[ srcOffset + 1 ] << 24) >>> 16) : 0 ) | |
479 | | ( numSigBytes > 2 ? ((source[ srcOffset + 2 ] << 24) >>> 24) : 0 ); | |
480 | ||
481 | switch( numSigBytes ) | |
482 | { | |
483 | case 3: | |
484 | destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; | |
485 | destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; | |
486 | destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ]; | |
487 | destination[ destOffset + 3 ] = ALPHABET[ (inBuff ) & 0x3f ]; | |
488 | return destination; | |
489 | ||
490 | case 2: | |
491 | destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; | |
492 | destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; | |
493 | destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ]; | |
494 | destination[ destOffset + 3 ] = EQUALS_SIGN; | |
495 | return destination; | |
496 | ||
497 | case 1: | |
498 | destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; | |
499 | destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; | |
500 | destination[ destOffset + 2 ] = EQUALS_SIGN; | |
501 | destination[ destOffset + 3 ] = EQUALS_SIGN; | |
502 | return destination; | |
503 | ||
504 | default: | |
505 | return destination; | |
506 | } // end switch | |
507 | } // end encode3to4 | |
508 | ||
509 | ||
510 | ||
511 | /** | |
512 | * Serializes an object and returns the Base64-encoded | |
513 | * version of that serialized object. If the object | |
514 | * cannot be serialized or there is another error, | |
515 | * the method will return <tt>null</tt>. | |
516 | * The object is not GZip-compressed before being encoded. | |
517 | * | |
518 | * @param serializableObject The object to encode | |
519 | * @return The Base64-encoded object | |
520 | * @since 1.4 | |
521 | */ | |
522 | public static String encodeObject( java.io.Serializable serializableObject ) | |
523 | { | |
524 | return encodeObject( serializableObject, NO_OPTIONS ); | |
525 | } // end encodeObject | |
526 | ||
527 | ||
528 | ||
529 | /** | |
530 | * Serializes an object and returns the Base64-encoded | |
531 | * version of that serialized object. If the object | |
532 | * cannot be serialized or there is another error, | |
533 | * the method will return <tt>null</tt>. | |
534 | * <p> | |
535 | * Valid options:<pre> | |
536 | * GZIP: gzip-compresses object before encoding it. | |
537 | * DONT_BREAK_LINES: don't break lines at 76 characters | |
538 | * <i>Note: Technically, this makes your encoding non-compliant.</i> | |
539 | * </pre> | |
540 | * <p> | |
541 | * Example: <code>encodeObject( myObj, Base64.GZIP )</code> or | |
542 | * <p> | |
543 | * Example: <code>encodeObject( myObj, Base64.GZIP | Base64.DONT_BREAK_LINES )</code> | |
544 | * | |
545 | * @param serializableObject The object to encode | |
546 | * @param options Specified options | |
547 | * @return The Base64-encoded object | |
548 | * @see Base64#GZIP | |
549 | * @see Base64#DONT_BREAK_LINES | |
550 | * @since 2.0 | |
551 | */ | |
552 | public static String encodeObject( java.io.Serializable serializableObject, int options ) | |
553 | { | |
554 | // Streams | |
555 | java.io.ByteArrayOutputStream baos = null; | |
556 | java.io.OutputStream b64os = null; | |
557 | java.io.ObjectOutputStream oos = null; | |
558 | java.util.zip.GZIPOutputStream gzos = null; | |
559 | ||
560 | // Isolate options | |
561 | int gzip = (options & GZIP); | |
562 | int dontBreakLines = (options & DONT_BREAK_LINES); | |
563 | ||
564 | try | |
565 | { | |
566 | // ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream | |
567 | baos = new java.io.ByteArrayOutputStream(); | |
568 | b64os = new Base64.OutputStream( baos, ENCODE | options ); | |
569 | ||
570 | // GZip? | |
571 | if( gzip == GZIP ) | |
572 | { | |
573 | gzos = new java.util.zip.GZIPOutputStream( b64os ); | |
574 | oos = new java.io.ObjectOutputStream( gzos ); | |
575 | } // end if: gzip | |
576 | else | |
577 | oos = new java.io.ObjectOutputStream( b64os ); | |
578 | ||
579 | oos.writeObject( serializableObject ); | |
580 | } // end try | |
581 | catch( java.io.IOException e ) | |
582 | { | |
583 | e.printStackTrace(); | |
584 | return null; | |
585 | } // end catch | |
586 | finally | |
587 | { | |
588 | try{ oos.close(); } catch( Exception e ){} | |
589 | try{ gzos.close(); } catch( Exception e ){} | |
590 | try{ b64os.close(); } catch( Exception e ){} | |
591 | try{ baos.close(); } catch( Exception e ){} | |
592 | } // end finally | |
593 | ||
594 | // Return value according to relevant encoding. | |
595 | try | |
596 | { | |
597 | return new String( baos.toByteArray(), PREFERRED_ENCODING ); | |
598 | } // end try | |
599 | catch (java.io.UnsupportedEncodingException uue) | |
600 | { | |
601 | return new String( baos.toByteArray() ); | |
602 | } // end catch | |
603 | ||
604 | } // end encode | |
605 | ||
606 | ||
607 | ||
608 | /** | |
609 | * Encodes a byte array into Base64 notation. | |
610 | * Does not GZip-compress data. | |
611 | * | |
612 | * @param source The data to convert | |
613 | * @since 1.4 | |
614 | */ | |
615 | public static String encodeBytes( byte[] source ) | |
616 | { | |
617 | return encodeBytes( source, 0, source.length, NO_OPTIONS ); | |
618 | } // end encodeBytes | |
619 | ||
620 | ||
621 | ||
622 | /** | |
623 | * Encodes a byte array into Base64 notation. | |
624 | * <p> | |
625 | * Valid options:<pre> | |
626 | * GZIP: gzip-compresses object before encoding it. | |
627 | * DONT_BREAK_LINES: don't break lines at 76 characters | |
628 | * <i>Note: Technically, this makes your encoding non-compliant.</i> | |
629 | * </pre> | |
630 | * <p> | |
631 | * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or | |
632 | * <p> | |
633 | * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code> | |
634 | * | |
635 | * | |
636 | * @param source The data to convert | |
637 | * @param options Specified options | |
638 | * @see Base64#GZIP | |
639 | * @see Base64#DONT_BREAK_LINES | |
640 | * @since 2.0 | |
641 | */ | |
642 | public static String encodeBytes( byte[] source, int options ) | |
643 | { | |
644 | return encodeBytes( source, 0, source.length, options ); | |
645 | } // end encodeBytes | |
646 | ||
647 | ||
648 | /** | |
649 | * Encodes a byte array into Base64 notation. | |
650 | * Does not GZip-compress data. | |
651 | * | |
652 | * @param source The data to convert | |
653 | * @param off Offset in array where conversion should begin | |
654 | * @param len Length of data to convert | |
655 | * @since 1.4 | |
656 | */ | |
657 | public static String encodeBytes( byte[] source, int off, int len ) | |
658 | { | |
659 | return encodeBytes( source, off, len, NO_OPTIONS ); | |
660 | } // end encodeBytes | |
661 | ||
662 | ||
663 | ||
664 | /** | |
665 | * Encodes a byte array into Base64 notation. | |
666 | * <p> | |
667 | * Valid options:<pre> | |
668 | * GZIP: gzip-compresses object before encoding it. | |
669 | * DONT_BREAK_LINES: don't break lines at 76 characters | |
670 | * <i>Note: Technically, this makes your encoding non-compliant.</i> | |
671 | * </pre> | |
672 | * <p> | |
673 | * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or | |
674 | * <p> | |
675 | * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code> | |
676 | * | |
677 | * | |
678 | * @param source The data to convert | |
679 | * @param off Offset in array where conversion should begin | |
680 | * @param len Length of data to convert | |
681 | * @param options Specified options | |
682 | * @param options alphabet type is pulled from this (standard, url-safe, ordered) | |
683 | * @see Base64#GZIP | |
684 | * @see Base64#DONT_BREAK_LINES | |
685 | * @since 2.0 | |
686 | */ | |
687 | public static String encodeBytes( byte[] source, int off, int len, int options ) | |
688 | { | |
689 | // Isolate options | |
690 | int dontBreakLines = ( options & DONT_BREAK_LINES ); | |
691 | int gzip = ( options & GZIP ); | |
692 | ||
693 | // Compress? | |
694 | if( gzip == GZIP ) | |
695 | { | |
696 | java.io.ByteArrayOutputStream baos = null; | |
697 | java.util.zip.GZIPOutputStream gzos = null; | |
698 | Base64.OutputStream b64os = null; | |
699 | ||
700 | ||
701 | try | |
702 | { | |
703 | // GZip -> Base64 -> ByteArray | |
704 | baos = new java.io.ByteArrayOutputStream(); | |
705 | b64os = new Base64.OutputStream( baos, ENCODE | options ); | |
706 | gzos = new java.util.zip.GZIPOutputStream( b64os ); | |
707 | ||
708 | gzos.write( source, off, len ); | |
709 | gzos.close(); | |
710 | } // end try | |
711 | catch( java.io.IOException e ) | |
712 | { | |
713 | e.printStackTrace(); | |
714 | return null; | |
715 | } // end catch | |
716 | finally | |
717 | { | |
718 | try{ gzos.close(); } catch( Exception e ){} | |
719 | try{ b64os.close(); } catch( Exception e ){} | |
720 | try{ baos.close(); } catch( Exception e ){} | |
721 | } // end finally | |
722 | ||
723 | // Return value according to relevant encoding. | |
724 | try | |
725 | { | |
726 | return new String( baos.toByteArray(), PREFERRED_ENCODING ); | |
727 | } // end try | |
728 | catch (java.io.UnsupportedEncodingException uue) | |
729 | { | |
730 | return new String( baos.toByteArray() ); | |
731 | } // end catch | |
732 | } // end if: compress | |
733 | ||
734 | // Else, don't compress. Better not to use streams at all then. | |
735 | else | |
736 | { | |
737 | // Convert option to boolean in way that code likes it. | |
738 | boolean breakLines = dontBreakLines == 0; | |
739 | ||
740 | int len43 = len * 4 / 3; | |
741 | byte[] outBuff = new byte[ ( len43 ) // Main 4:3 | |
742 | + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding | |
743 | + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines | |
744 | int d = 0; | |
745 | int e = 0; | |
746 | int len2 = len - 2; | |
747 | int lineLength = 0; | |
748 | for( ; d < len2; d+=3, e+=4 ) | |
749 | { | |
750 | encode3to4( source, d+off, 3, outBuff, e, options ); | |
751 | ||
752 | lineLength += 4; | |
753 | if( breakLines && lineLength == MAX_LINE_LENGTH ) | |
754 | { | |
755 | outBuff[e+4] = NEW_LINE; | |
756 | e++; | |
757 | lineLength = 0; | |
758 | } // end if: end of line | |
759 | } // en dfor: each piece of array | |
760 | ||
761 | if( d < len ) | |
762 | { | |
763 | encode3to4( source, d+off, len - d, outBuff, e, options ); | |
764 | e += 4; | |
765 | } // end if: some padding needed | |
766 | ||
767 | ||
768 | // Return value according to relevant encoding. | |
769 | try | |
770 | { | |
771 | return new String( outBuff, 0, e, PREFERRED_ENCODING ); | |
772 | } // end try | |
773 | catch (java.io.UnsupportedEncodingException uue) | |
774 | { | |
775 | return new String( outBuff, 0, e ); | |
776 | } // end catch | |
777 | ||
778 | } // end else: don't compress | |
779 | ||
780 | } // end encodeBytes | |
781 | ||
782 | ||
783 | ||
784 | ||
785 | ||
786 | /* ******** D E C O D I N G M E T H O D S ******** */ | |
787 | ||
788 | ||
789 | /** | |
790 | * Decodes four bytes from array <var>source</var> | |
791 | * and writes the resulting bytes (up to three of them) | |
792 | * to <var>destination</var>. | |
793 | * The source and destination arrays can be manipulated | |
794 | * anywhere along their length by specifying | |
795 | * <var>srcOffset</var> and <var>destOffset</var>. | |
796 | * This method does not check to make sure your arrays | |
797 | * are large enough to accomodate <var>srcOffset</var> + 4 for | |
798 | * the <var>source</var> array or <var>destOffset</var> + 3 for | |
799 | * the <var>destination</var> array. | |
800 | * This method returns the actual number of bytes that | |
801 | * were converted from the Base64 encoding. | |
802 | * <p>This is the lowest level of the decoding methods with | |
803 | * all possible parameters.</p> | |
804 | * | |
805 | * | |
806 | * @param source the array to convert | |
807 | * @param srcOffset the index where conversion begins | |
808 | * @param destination the array to hold the conversion | |
809 | * @param destOffset the index where output will be put | |
810 | * @param options alphabet type is pulled from this (standard, url-safe, ordered) | |
811 | * @return the number of decoded bytes converted | |
812 | * @since 1.3 | |
813 | */ | |
814 | private static int decode4to3( byte[] source, int srcOffset, byte[] destination, int destOffset, int options ) | |
815 | { | |
816 | byte[] DECODABET = getDecodabet( options ); | |
817 | ||
818 | // Example: Dk== | |
819 | if( source[ srcOffset + 2] == EQUALS_SIGN ) | |
820 | { | |
821 | // Two ways to do the same thing. Don't know which way I like best. | |
822 | //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) | |
823 | // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 ); | |
824 | int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) | |
825 | | ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 ); | |
826 | ||
827 | destination[ destOffset ] = (byte)( outBuff >>> 16 ); | |
828 | return 1; | |
829 | } | |
830 | ||
831 | // Example: DkL= | |
832 | else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) | |
833 | { | |
834 | // Two ways to do the same thing. Don't know which way I like best. | |
835 | //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) | |
836 | // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) | |
837 | // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ); | |
838 | int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) | |
839 | | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 ) | |
840 | | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 ); | |
841 | ||
842 | destination[ destOffset ] = (byte)( outBuff >>> 16 ); | |
843 | destination[ destOffset + 1 ] = (byte)( outBuff >>> 8 ); | |
844 | return 2; | |
845 | } | |
846 | ||
847 | // Example: DkLE | |
848 | else | |
849 | { | |
850 | try{ | |
851 | // Two ways to do the same thing. Don't know which way I like best. | |
852 | //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) | |
853 | // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) | |
854 | // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ) | |
855 | // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 ); | |
856 | int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) | |
857 | | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 ) | |
858 | | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6) | |
859 | | ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) ); | |
860 | ||
861 | ||
862 | destination[ destOffset ] = (byte)( outBuff >> 16 ); | |
863 | destination[ destOffset + 1 ] = (byte)( outBuff >> 8 ); | |
864 | destination[ destOffset + 2 ] = (byte)( outBuff ); | |
865 | ||
866 | return 3; | |
867 | }catch( Exception e){ | |
868 | System.out.println(""+source[srcOffset]+ ": " + ( DECODABET[ source[ srcOffset ] ] ) ); | |
869 | System.out.println(""+source[srcOffset+1]+ ": " + ( DECODABET[ source[ srcOffset + 1 ] ] ) ); | |
870 | System.out.println(""+source[srcOffset+2]+ ": " + ( DECODABET[ source[ srcOffset + 2 ] ] ) ); | |
871 | System.out.println(""+source[srcOffset+3]+ ": " + ( DECODABET[ source[ srcOffset + 3 ] ] ) ); | |
872 | return -1; | |
873 | } // end catch | |
874 | } | |
875 | } // end decodeToBytes | |
876 | ||
877 | ||
878 | ||
879 | ||
880 | /** | |
881 | * Very low-level access to decoding ASCII characters in | |
882 | * the form of a byte array. Does not support automatically | |
883 | * gunzipping or any other "fancy" features. | |
884 | * | |
885 | * @param source The Base64 encoded data | |
886 | * @param off The offset of where to begin decoding | |
887 | * @param len The length of characters to decode | |
888 | * @return decoded data | |
889 | * @since 1.3 | |
890 | */ | |
891 | public static byte[] decode( byte[] source, int off, int len, int options ) | |
892 | { | |
893 | byte[] DECODABET = getDecodabet( options ); | |
894 | ||
895 | int len34 = len * 3 / 4; | |
896 | byte[] outBuff = new byte[ len34 ]; // Upper limit on size of output | |
897 | int outBuffPosn = 0; | |
898 | ||
899 | byte[] b4 = new byte[4]; | |
900 | int b4Posn = 0; | |
901 | int i = 0; | |
902 | byte sbiCrop = 0; | |
903 | byte sbiDecode = 0; | |
904 | for( i = off; i < off+len; i++ ) | |
905 | { | |
906 | sbiCrop = (byte)(source[i] & 0x7f); // Only the low seven bits | |
907 | sbiDecode = DECODABET[ sbiCrop ]; | |
908 | ||
909 | if( sbiDecode >= WHITE_SPACE_ENC ) // White space, Equals sign or better | |
910 | { | |
911 | if( sbiDecode >= EQUALS_SIGN_ENC ) | |
912 | { | |
913 | b4[ b4Posn++ ] = sbiCrop; | |
914 | if( b4Posn > 3 ) | |
915 | { | |
916 | outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn, options ); | |
917 | b4Posn = 0; | |
918 | ||
919 | // If that was the equals sign, break out of 'for' loop | |
920 | if( sbiCrop == EQUALS_SIGN ) | |
921 | break; | |
922 | } // end if: quartet built | |
923 | ||
924 | } // end if: equals sign or better | |
925 | ||
926 | } // end if: white space, equals sign or better | |
927 | else | |
928 | { | |
929 | System.err.println( "Bad Base64 input character at " + i + ": " + source[i] + "(decimal)" ); | |
930 | return null; | |
931 | } // end else: | |
932 | } // each input character | |
933 | ||
934 | byte[] out = new byte[ outBuffPosn ]; | |
935 | System.arraycopy( outBuff, 0, out, 0, outBuffPosn ); | |
936 | return out; | |
937 | } // end decode | |
938 | ||
939 | ||
940 | ||
941 | ||
942 | /** | |
943 | * Decodes data from Base64 notation, automatically | |
944 | * detecting gzip-compressed data and decompressing it. | |
945 | * | |
946 | * @param s the string to decode | |
947 | * @return the decoded data | |
948 | * @since 1.4 | |
949 | */ | |
950 | public static byte[] decode( String s ) | |
951 | { | |
952 | return decode( s, NO_OPTIONS ); | |
953 | } | |
954 | ||
955 | ||
956 | /** | |
957 | * Decodes data from Base64 notation, automatically | |
958 | * detecting gzip-compressed data and decompressing it. | |
959 | * | |
960 | * @param s the string to decode | |
961 | * @param options encode options such as URL_SAFE | |
962 | * @return the decoded data | |
963 | * @since 1.4 | |
964 | */ | |
965 | public static byte[] decode( String s, int options ) | |
966 | { | |
967 | byte[] bytes; | |
968 | try | |
969 | { | |
970 | bytes = s.getBytes( PREFERRED_ENCODING ); | |
971 | } // end try | |
972 | catch( java.io.UnsupportedEncodingException uee ) | |
973 | { | |
974 | bytes = s.getBytes(); | |
975 | } // end catch | |
976 | //</change> | |
977 | ||
978 | // Decode | |
979 | bytes = decode( bytes, 0, bytes.length, options ); | |
980 | ||
981 | ||
982 | // Check to see if it's gzip-compressed | |
983 | // GZIP Magic Two-Byte Number: 0x8b1f (35615) | |
984 | if( (options & NO_GZIP_MAGIC) == 0 | |
985 | && bytes != null && bytes.length >= 4 ) | |
986 | { | |
987 | ||
988 | int head = ((int)bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00); | |
989 | if( java.util.zip.GZIPInputStream.GZIP_MAGIC == head ) | |
990 | { | |
991 | java.io.ByteArrayInputStream bais = null; | |
992 | java.util.zip.GZIPInputStream gzis = null; | |
993 | java.io.ByteArrayOutputStream baos = null; | |
994 | byte[] buffer = new byte[2048]; | |
995 | int length = 0; | |
996 | ||
997 | try | |
998 | { | |
999 | baos = new java.io.ByteArrayOutputStream(); | |
1000 | bais = new java.io.ByteArrayInputStream( bytes ); | |
1001 | gzis = new java.util.zip.GZIPInputStream( bais ); | |
1002 | ||
1003 | while( ( length = gzis.read( buffer ) ) >= 0 ) | |
1004 | { | |
1005 | baos.write(buffer,0,length); | |
1006 | } // end while: reading input | |
1007 | ||
1008 | // No error? Get new bytes. | |
1009 | bytes = baos.toByteArray(); | |
1010 | ||
1011 | } // end try | |
1012 | catch( java.io.IOException e ) | |
1013 | { | |
1014 | // Just return originally-decoded bytes | |
1015 | } // end catch | |
1016 | finally | |
1017 | { | |
1018 | try{ baos.close(); } catch( Exception e ){} | |
1019 | try{ gzis.close(); } catch( Exception e ){} | |
1020 | try{ bais.close(); } catch( Exception e ){} | |
1021 | } // end finally | |
1022 | ||
1023 | } // end if: gzipped | |
1024 | } // end if: bytes.length >= 2 | |
1025 | ||
1026 | return bytes; | |
1027 | } // end decode | |
1028 | ||
1029 | ||
1030 | ||
1031 | ||
1032 | /** | |
1033 | * Attempts to decode Base64 data and deserialize a Java | |
1034 | * Object within. Returns <tt>null</tt> if there was an error. | |
1035 | * | |
1036 | * @param encodedObject The Base64 data to decode | |
1037 | * @return The decoded and deserialized object | |
1038 | * @since 1.5 | |
1039 | */ | |
1040 | public static Object decodeToObject( String encodedObject ) | |
1041 | { | |
1042 | // Decode and gunzip if necessary | |
1043 | byte[] objBytes = decode( encodedObject ); | |
1044 | ||
1045 | java.io.ByteArrayInputStream bais = null; | |
1046 | java.io.ObjectInputStream ois = null; | |
1047 | Object obj = null; | |
1048 | ||
1049 | try | |
1050 | { | |
1051 | bais = new java.io.ByteArrayInputStream( objBytes ); | |
1052 | ois = new java.io.ObjectInputStream( bais ); | |
1053 | ||
1054 | obj = ois.readObject(); | |
1055 | } // end try | |
1056 | catch( java.io.IOException e ) | |
1057 | { | |
1058 | e.printStackTrace(); | |
1059 | obj = null; | |
1060 | } // end catch | |
1061 | catch( java.lang.ClassNotFoundException e ) | |
1062 | { | |
1063 | e.printStackTrace(); | |
1064 | obj = null; | |
1065 | } // end catch | |
1066 | finally | |
1067 | { | |
1068 | try{ bais.close(); } catch( Exception e ){} | |
1069 | try{ ois.close(); } catch( Exception e ){} | |
1070 | } // end finally | |
1071 | ||
1072 | return obj; | |
1073 | } // end decodeObject | |
1074 | ||
1075 | ||
1076 | ||
1077 | /** | |
1078 | * Convenience method for encoding data to a file. | |
1079 | * | |
1080 | * @param dataToEncode byte array of data to encode in base64 form | |
1081 | * @param filename Filename for saving encoded data | |
1082 | * @return <tt>true</tt> if successful, <tt>false</tt> otherwise | |
1083 | * | |
1084 | * @since 2.1 | |
1085 | */ | |
1086 | public static boolean encodeToFile( byte[] dataToEncode, String filename ) | |
1087 | { | |
1088 | boolean success = false; | |
1089 | Base64.OutputStream bos = null; | |
1090 | try | |
1091 | { | |
1092 | bos = new Base64.OutputStream( | |
1093 | new java.io.FileOutputStream( filename ), Base64.ENCODE ); | |
1094 | bos.write( dataToEncode ); | |
1095 | success = true; | |
1096 | } // end try | |
1097 | catch( java.io.IOException e ) | |
1098 | { | |
1099 | ||
1100 | success = false; | |
1101 | } // end catch: IOException | |
1102 | finally | |
1103 | { | |
1104 | try{ bos.close(); } catch( Exception e ){} | |
1105 | } // end finally | |
1106 | ||
1107 | return success; | |
1108 | } // end encodeToFile | |
1109 | ||
1110 | ||
1111 | /** | |
1112 | * Convenience method for decoding data to a file. | |
1113 | * | |
1114 | * @param dataToDecode Base64-encoded data as a string | |
1115 | * @param filename Filename for saving decoded data | |
1116 | * @return <tt>true</tt> if successful, <tt>false</tt> otherwise | |
1117 | * | |
1118 | * @since 2.1 | |
1119 | */ | |
1120 | public static boolean decodeToFile( String dataToDecode, String filename ) | |
1121 | { | |
1122 | boolean success = false; | |
1123 | Base64.OutputStream bos = null; | |
1124 | try | |
1125 | { | |
1126 | bos = new Base64.OutputStream( | |
1127 | new java.io.FileOutputStream( filename ), Base64.DECODE ); | |
1128 | bos.write( dataToDecode.getBytes( PREFERRED_ENCODING ) ); | |
1129 | success = true; | |
1130 | } // end try | |
1131 | catch( java.io.IOException e ) | |
1132 | { | |
1133 | success = false; | |
1134 | } // end catch: IOException | |
1135 | finally | |
1136 | { | |
1137 | try{ bos.close(); } catch( Exception e ){} | |
1138 | } // end finally | |
1139 | ||
1140 | return success; | |
1141 | } // end decodeToFile | |
1142 | ||
1143 | ||
1144 | ||
1145 | ||
1146 | /** | |
1147 | * Convenience method for reading a base64-encoded | |
1148 | * file and decoding it. | |
1149 | * | |
1150 | * @param filename Filename for reading encoded data | |
1151 | * @return decoded byte array or null if unsuccessful | |
1152 | * | |
1153 | * @since 2.1 | |
1154 | */ | |
1155 | public static byte[] decodeFromFile( String filename ) | |
1156 | { | |
1157 | byte[] decodedData = null; | |
1158 | Base64.InputStream bis = null; | |
1159 | try | |
1160 | { | |
1161 | // Set up some useful variables | |
1162 | java.io.File file = new java.io.File( filename ); | |
1163 | byte[] buffer = null; | |
1164 | int length = 0; | |
1165 | int numBytes = 0; | |
1166 | ||
1167 | // Check for size of file | |
1168 | if( file.length() > Integer.MAX_VALUE ) | |
1169 | { | |
1170 | System.err.println( "File is too big for this convenience method (" + file.length() + " bytes)." ); | |
1171 | return null; | |
1172 | } // end if: file too big for int index | |
1173 | buffer = new byte[ (int)file.length() ]; | |
1174 | ||
1175 | // Open a stream | |
1176 | bis = new Base64.InputStream( | |
1177 | new java.io.BufferedInputStream( | |
1178 | new java.io.FileInputStream( file ) ), Base64.DECODE ); | |
1179 | ||
1180 | // Read until done | |
1181 | while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) | |
1182 | length += numBytes; | |
1183 | ||
1184 | // Save in a variable to return | |
1185 | decodedData = new byte[ length ]; | |
1186 | System.arraycopy( buffer, 0, decodedData, 0, length ); | |
1187 | ||
1188 | } // end try | |
1189 | catch( java.io.IOException e ) | |
1190 | { | |
1191 | System.err.println( "Error decoding from file " + filename ); | |
1192 | } // end catch: IOException | |
1193 | finally | |
1194 | { | |
1195 | try{ bis.close(); } catch( Exception e) {} | |
1196 | } // end finally | |
1197 | ||
1198 | return decodedData; | |
1199 | } // end decodeFromFile | |
1200 | ||
1201 | ||
1202 | ||
1203 | /** | |
1204 | * Convenience method for reading a binary file | |
1205 | * and base64-encoding it. | |
1206 | * | |
1207 | * @param filename Filename for reading binary data | |
1208 | * @return base64-encoded string or null if unsuccessful | |
1209 | * | |
1210 | * @since 2.1 | |
1211 | */ | |
1212 | public static String encodeFromFile( String filename ) | |
1213 | { | |
1214 | String encodedData = null; | |
1215 | Base64.InputStream bis = null; | |
1216 | try | |
1217 | { | |
1218 | // Set up some useful variables | |
1219 | java.io.File file = new java.io.File( filename ); | |
1220 | byte[] buffer = new byte[ Math.max((int)(file.length() * 1.4),40) ]; // Need max() for math on small files (v2.2.1) | |
1221 | int length = 0; | |
1222 | int numBytes = 0; | |
1223 | ||
1224 | // Open a stream | |
1225 | bis = new Base64.InputStream( | |
1226 | new java.io.BufferedInputStream( | |
1227 | new java.io.FileInputStream( file ) ), Base64.ENCODE ); | |
1228 | ||
1229 | // Read until done | |
1230 | while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) | |
1231 | length += numBytes; | |
1232 | ||
1233 | // Save in a variable to return | |
1234 | encodedData = new String( buffer, 0, length, Base64.PREFERRED_ENCODING ); | |
1235 | ||
1236 | } // end try | |
1237 | catch( java.io.IOException e ) | |
1238 | { | |
1239 | System.err.println( "Error encoding from file " + filename ); | |
1240 | } // end catch: IOException | |
1241 | finally | |
1242 | { | |
1243 | try{ bis.close(); } catch( Exception e) {} | |
1244 | } // end finally | |
1245 | ||
1246 | return encodedData; | |
1247 | } // end encodeFromFile | |
1248 | ||
1249 | /** | |
1250 | * Reads <tt>infile</tt> and encodes it to <tt>outfile</tt>. | |
1251 | * | |
1252 | * @param infile Input file | |
1253 | * @param outfile Output file | |
1254 | * @since 2.2 | |
1255 | */ | |
1256 | public static void encodeFileToFile( String infile, String outfile ) | |
1257 | { | |
1258 | String encoded = Base64.encodeFromFile( infile ); | |
1259 | java.io.OutputStream out = null; | |
1260 | try{ | |
1261 | out = new java.io.BufferedOutputStream( | |
1262 | new java.io.FileOutputStream( outfile ) ); | |
1263 | out.write( encoded.getBytes("US-ASCII") ); // Strict, 7-bit output. | |
1264 | } // end try | |
1265 | catch( java.io.IOException ex ) { | |
1266 | ex.printStackTrace(); | |
1267 | } // end catch | |
1268 | finally { | |
1269 | try { out.close(); } | |
1270 | catch( Exception ex ){} | |
1271 | } // end finally | |
1272 | } // end encodeFileToFile | |
1273 | ||
1274 | ||
1275 | /** | |
1276 | * Reads <tt>infile</tt> and decodes it to <tt>outfile</tt>. | |
1277 | * | |
1278 | * @param infile Input file | |
1279 | * @param outfile Output file | |
1280 | * @since 2.2 | |
1281 | */ | |
1282 | public static void decodeFileToFile( String infile, String outfile ) | |
1283 | { | |
1284 | byte[] decoded = Base64.decodeFromFile( infile ); | |
1285 | java.io.OutputStream out = null; | |
1286 | try{ | |
1287 | out = new java.io.BufferedOutputStream( | |
1288 | new java.io.FileOutputStream( outfile ) ); | |
1289 | out.write( decoded ); | |
1290 | } // end try | |
1291 | catch( java.io.IOException ex ) { | |
1292 | ex.printStackTrace(); | |
1293 | } // end catch | |
1294 | finally { | |
1295 | try { out.close(); } | |
1296 | catch( Exception ex ){} | |
1297 | } // end finally | |
1298 | } // end decodeFileToFile | |
1299 | ||
1300 | ||
1301 | /* ******** I N N E R C L A S S I N P U T S T R E A M ******** */ | |
1302 | ||
1303 | ||
1304 | ||
1305 | /** | |
1306 | * A {@link Base64.InputStream} will read data from another | |
1307 | * <tt>java.io.InputStream</tt>, given in the constructor, | |
1308 | * and encode/decode to/from Base64 notation on the fly. | |
1309 | * | |
1310 | * @see Base64 | |
1311 | * @since 1.3 | |
1312 | */ | |
1313 | public static class InputStream extends java.io.FilterInputStream | |
1314 | { | |
1315 | private boolean encode; // Encoding or decoding | |
1316 | private int position; // Current position in the buffer | |
1317 | private byte[] buffer; // Small buffer holding converted data | |
1318 | private int bufferLength; // Length of buffer (3 or 4) | |
1319 | private int numSigBytes; // Number of meaningful bytes in the buffer | |
1320 | private int lineLength; | |
1321 | private boolean breakLines; // Break lines at less than 80 characters | |
1322 | private int options; // Record options used to create the stream. | |
1323 | private byte[] alphabet; // Local copies to avoid extra method calls | |
1324 | private byte[] decodabet; // Local copies to avoid extra method calls | |
1325 | ||
1326 | ||
1327 | /** | |
1328 | * Constructs a {@link Base64.InputStream} in DECODE mode. | |
1329 | * | |
1330 | * @param in the <tt>java.io.InputStream</tt> from which to read data. | |
1331 | * @since 1.3 | |
1332 | */ | |
1333 | public InputStream( java.io.InputStream in ) | |
1334 | { | |
1335 | this( in, DECODE ); | |
1336 | } // end constructor | |
1337 | ||
1338 | ||
1339 | /** | |
1340 | * Constructs a {@link Base64.InputStream} in | |
1341 | * either ENCODE or DECODE mode. | |
1342 | * <p> | |
1343 | * Valid options:<pre> | |
1344 | * ENCODE or DECODE: Encode or Decode as data is read. | |
1345 | * DONT_BREAK_LINES: don't break lines at 76 characters | |
1346 | * (only meaningful when encoding) | |
1347 | * <i>Note: Technically, this makes your encoding non-compliant.</i> | |
1348 | * </pre> | |
1349 | * <p> | |
1350 | * Example: <code>new Base64.InputStream( in, Base64.DECODE )</code> | |
1351 | * | |
1352 | * | |
1353 | * @param in the <tt>java.io.InputStream</tt> from which to read data. | |
1354 | * @param options Specified options | |
1355 | * @see Base64#ENCODE | |
1356 | * @see Base64#DECODE | |
1357 | * @see Base64#DONT_BREAK_LINES | |
1358 | * @since 2.0 | |
1359 | */ | |
1360 | public InputStream( java.io.InputStream in, int options ) | |
1361 | { | |
1362 | super( in ); | |
1363 | this.breakLines = (options & DONT_BREAK_LINES) != DONT_BREAK_LINES; | |
1364 | this.encode = (options & ENCODE) == ENCODE; | |
1365 | this.bufferLength = encode ? 4 : 3; | |
1366 | this.buffer = new byte[ bufferLength ]; | |
1367 | this.position = -1; | |
1368 | this.lineLength = 0; | |
1369 | this.options = options; // Record for later, mostly to determine which alphabet to use | |
1370 | this.alphabet = getAlphabet(options); | |
1371 | this.decodabet = getDecodabet(options); | |
1372 | } // end constructor | |
1373 | ||
1374 | /** | |
1375 | * Reads enough of the input stream to convert | |
1376 | * to/from Base64 and returns the next byte. | |
1377 | * | |
1378 | * @return next byte | |
1379 | * @since 1.3 | |
1380 | */ | |
1381 | public int read() throws java.io.IOException | |
1382 | { | |
1383 | // Do we need to get data? | |
1384 | if( position < 0 ) | |
1385 | { | |
1386 | if( encode ) | |
1387 | { | |
1388 | byte[] b3 = new byte[3]; | |
1389 | int numBinaryBytes = 0; | |
1390 | for( int i = 0; i < 3; i++ ) | |
1391 | { | |
1392 | try | |
1393 | { | |
1394 | int b = in.read(); | |
1395 | ||
1396 | // If end of stream, b is -1. | |
1397 | if( b >= 0 ) | |
1398 | { | |
1399 | b3[i] = (byte)b; | |
1400 | numBinaryBytes++; | |
1401 | } // end if: not end of stream | |
1402 | ||
1403 | } // end try: read | |
1404 | catch( java.io.IOException e ) | |
1405 | { | |
1406 | // Only a problem if we got no data at all. | |
1407 | if( i == 0 ) | |
1408 | throw e; | |
1409 | ||
1410 | } // end catch | |
1411 | } // end for: each needed input byte | |
1412 | ||
1413 | if( numBinaryBytes > 0 ) | |
1414 | { | |
1415 | encode3to4( b3, 0, numBinaryBytes, buffer, 0, options ); | |
1416 | position = 0; | |
1417 | numSigBytes = 4; | |
1418 | } // end if: got data | |
1419 | else | |
1420 | { | |
1421 | return -1; | |
1422 | } // end else | |
1423 | } // end if: encoding | |
1424 | ||
1425 | // Else decoding | |
1426 | else | |
1427 | { | |
1428 | byte[] b4 = new byte[4]; | |
1429 | int i = 0; | |
1430 | for( i = 0; i < 4; i++ ) | |
1431 | { | |
1432 | // Read four "meaningful" bytes: | |
1433 | int b = 0; | |
1434 | do{ b = in.read(); } | |
1435 | while( b >= 0 && decodabet[ b & 0x7f ] <= WHITE_SPACE_ENC ); | |
1436 | ||
1437 | if( b < 0 ) | |
1438 | break; // Reads a -1 if end of stream | |
1439 | ||
1440 | b4[i] = (byte)b; | |
1441 | } // end for: each needed input byte | |
1442 | ||
1443 | if( i == 4 ) | |
1444 | { | |
1445 | numSigBytes = decode4to3( b4, 0, buffer, 0, options ); | |
1446 | position = 0; | |
1447 | } // end if: got four characters | |
1448 | else if( i == 0 ){ | |
1449 | return -1; | |
1450 | } // end else if: also padded correctly | |
1451 | else | |
1452 | { | |
1453 | // Must have broken out from above. | |
1454 | throw new java.io.IOException( "Improperly padded Base64 input." ); | |
1455 | } // end | |
1456 | ||
1457 | } // end else: decode | |
1458 | } // end else: get data | |
1459 | ||
1460 | // Got data? | |
1461 | if( position >= 0 ) | |
1462 | { | |
1463 | // End of relevant data? | |
1464 | if( /*!encode &&*/ position >= numSigBytes ) | |
1465 | return -1; | |
1466 | ||
1467 | if( encode && breakLines && lineLength >= MAX_LINE_LENGTH ) | |
1468 | { | |
1469 | lineLength = 0; | |
1470 | return '\n'; | |
1471 | } // end if | |
1472 | else | |
1473 | { | |
1474 | lineLength++; // This isn't important when decoding | |
1475 | // but throwing an extra "if" seems | |
1476 | // just as wasteful. | |
1477 | ||
1478 | int b = buffer[ position++ ]; | |
1479 | ||
1480 | if( position >= bufferLength ) | |
1481 | position = -1; | |
1482 | ||
1483 | return b & 0xFF; // This is how you "cast" a byte that's | |
1484 | // intended to be unsigned. | |
1485 | } // end else | |
1486 | } // end if: position >= 0 | |
1487 | ||
1488 | // Else error | |
1489 | else | |
1490 | { | |
1491 | // When JDK1.4 is more accepted, use an assertion here. | |
1492 | throw new java.io.IOException( "Error in Base64 code reading stream." ); | |
1493 | } // end else | |
1494 | } // end read | |
1495 | ||
1496 | ||
1497 | /** | |
1498 | * Calls {@link #read()} repeatedly until the end of stream | |
1499 | * is reached or <var>len</var> bytes are read. | |
1500 | * Returns number of bytes read into array or -1 if | |
1501 | * end of stream is encountered. | |
1502 | * | |
1503 | * @param dest array to hold values | |
1504 | * @param off offset for array | |
1505 | * @param len max number of bytes to read into array | |
1506 | * @return bytes read into array or -1 if end of stream is encountered. | |
1507 | * @since 1.3 | |
1508 | */ | |
1509 | public int read( byte[] dest, int off, int len ) throws java.io.IOException | |
1510 | { | |
1511 | int i; | |
1512 | int b; | |
1513 | for( i = 0; i < len; i++ ) | |
1514 | { | |
1515 | b = read(); | |
1516 | ||
1517 | //if( b < 0 && i == 0 ) | |
1518 | // return -1; | |
1519 | ||
1520 | if( b >= 0 ) | |
1521 | dest[off + i] = (byte)b; | |
1522 | else if( i == 0 ) | |
1523 | return -1; | |
1524 | else | |
1525 | break; // Out of 'for' loop | |
1526 | } // end for: each byte read | |
1527 | return i; | |
1528 | } // end read | |
1529 | ||
1530 | } // end inner class InputStream | |
1531 | ||
1532 | ||
1533 | ||
1534 | ||
1535 | ||
1536 | ||
1537 | /* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */ | |
1538 | ||
1539 | ||
1540 | ||
1541 | /** | |
1542 | * A {@link Base64.OutputStream} will write data to another | |
1543 | * <tt>java.io.OutputStream</tt>, given in the constructor, | |
1544 | * and encode/decode to/from Base64 notation on the fly. | |
1545 | * | |
1546 | * @see Base64 | |
1547 | * @since 1.3 | |
1548 | */ | |
1549 | public static class OutputStream extends java.io.FilterOutputStream | |
1550 | { | |
1551 | private boolean encode; | |
1552 | private int position; | |
1553 | private byte[] buffer; | |
1554 | private int bufferLength; | |
1555 | private int lineLength; | |
1556 | private boolean breakLines; | |
1557 | private byte[] b4; // Scratch used in a few places | |
1558 | private boolean suspendEncoding; | |
1559 | private int options; // Record for later | |
1560 | private byte[] alphabet; // Local copies to avoid extra method calls | |
1561 | private byte[] decodabet; // Local copies to avoid extra method calls | |
1562 | ||
1563 | /** | |
1564 | * Constructs a {@link Base64.OutputStream} in ENCODE mode. | |
1565 | * | |
1566 | * @param out the <tt>java.io.OutputStream</tt> to which data will be written. | |
1567 | * @since 1.3 | |
1568 | */ | |
1569 | public OutputStream( java.io.OutputStream out ) | |
1570 | { | |
1571 | this( out, ENCODE ); | |
1572 | } // end constructor | |
1573 | ||
1574 | ||
1575 | /** | |
1576 | * Constructs a {@link Base64.OutputStream} in | |
1577 | * either ENCODE or DECODE mode. | |
1578 | * <p> | |
1579 | * Valid options:<pre> | |
1580 | * ENCODE or DECODE: Encode or Decode as data is read. | |
1581 | * DONT_BREAK_LINES: don't break lines at 76 characters | |
1582 | * (only meaningful when encoding) | |
1583 | * <i>Note: Technically, this makes your encoding non-compliant.</i> | |
1584 | * </pre> | |
1585 | * <p> | |
1586 | * Example: <code>new Base64.OutputStream( out, Base64.ENCODE )</code> | |
1587 | * | |
1588 | * @param out the <tt>java.io.OutputStream</tt> to which data will be written. | |
1589 | * @param options Specified options. | |
1590 | * @see Base64#ENCODE | |
1591 | * @see Base64#DECODE | |
1592 | * @see Base64#DONT_BREAK_LINES | |
1593 | * @since 1.3 | |
1594 | */ | |
1595 | public OutputStream( java.io.OutputStream out, int options ) | |
1596 | { | |
1597 | super( out ); | |
1598 | this.breakLines = (options & DONT_BREAK_LINES) != DONT_BREAK_LINES; | |
1599 | this.encode = (options & ENCODE) == ENCODE; | |
1600 | this.bufferLength = encode ? 3 : 4; | |
1601 | this.buffer = new byte[ bufferLength ]; | |
1602 | this.position = 0; | |
1603 | this.lineLength = 0; | |
1604 | this.suspendEncoding = false; | |
1605 | this.b4 = new byte[4]; | |
1606 | this.options = options; | |
1607 | this.alphabet = getAlphabet(options); | |
1608 | this.decodabet = getDecodabet(options); | |
1609 | } // end constructor | |
1610 | ||
1611 | ||
1612 | /** | |
1613 | * Writes the byte to the output stream after | |
1614 | * converting to/from Base64 notation. | |
1615 | * When encoding, bytes are buffered three | |
1616 | * at a time before the output stream actually | |
1617 | * gets a write() call. | |
1618 | * When decoding, bytes are buffered four | |
1619 | * at a time. | |
1620 | * | |
1621 | * @param theByte the byte to write | |
1622 | * @since 1.3 | |
1623 | */ | |
1624 | public void write(int theByte) throws java.io.IOException | |
1625 | { | |
1626 | // Encoding suspended? | |
1627 | if( suspendEncoding ) | |
1628 | { | |
1629 | super.out.write( theByte ); | |
1630 | return; | |
1631 | } // end if: supsended | |
1632 | ||
1633 | // Encode? | |
1634 | if( encode ) | |
1635 | { | |
1636 | buffer[ position++ ] = (byte)theByte; | |
1637 | if( position >= bufferLength ) // Enough to encode. | |
1638 | { | |
1639 | out.write( encode3to4( b4, buffer, bufferLength, options ) ); | |
1640 | ||
1641 | lineLength += 4; | |
1642 | if( breakLines && lineLength >= MAX_LINE_LENGTH ) | |
1643 | { | |
1644 | out.write( NEW_LINE ); | |
1645 | lineLength = 0; | |
1646 | } // end if: end of line | |
1647 | ||
1648 | position = 0; | |
1649 | } // end if: enough to output | |
1650 | } // end if: encoding | |
1651 | ||
1652 | // Else, Decoding | |
1653 | else | |
1654 | { | |
1655 | // Meaningful Base64 character? | |
1656 | if( decodabet[ theByte & 0x7f ] > WHITE_SPACE_ENC ) | |
1657 | { | |
1658 | buffer[ position++ ] = (byte)theByte; | |
1659 | if( position >= bufferLength ) // Enough to output. | |
1660 | { | |
1661 | int len = Base64.decode4to3( buffer, 0, b4, 0, options ); | |
1662 | out.write( b4, 0, len ); | |
1663 | //out.write( Base64.decode4to3( buffer ) ); | |
1664 | position = 0; | |
1665 | } // end if: enough to output | |
1666 | } // end if: meaningful base64 character | |
1667 | else if( decodabet[ theByte & 0x7f ] != WHITE_SPACE_ENC ) | |
1668 | { | |
1669 | throw new java.io.IOException( "Invalid character in Base64 data." ); | |
1670 | } // end else: not white space either | |
1671 | } // end else: decoding | |
1672 | } // end write | |
1673 | ||
1674 | ||
1675 | ||
1676 | /** | |
1677 | * Calls {@link #write(int)} repeatedly until <var>len</var> | |
1678 | * bytes are written. | |
1679 | * | |
1680 | * @param theBytes array from which to read bytes | |
1681 | * @param off offset for array | |
1682 | * @param len max number of bytes to read into array | |
1683 | * @since 1.3 | |
1684 | */ | |
1685 | public void write( byte[] theBytes, int off, int len ) throws java.io.IOException | |
1686 | { | |
1687 | // Encoding suspended? | |
1688 | if( suspendEncoding ) | |
1689 | { | |
1690 | super.out.write( theBytes, off, len ); | |
1691 | return; | |
1692 | } // end if: supsended | |
1693 | ||
1694 | for( int i = 0; i < len; i++ ) | |
1695 | { | |
1696 | write( theBytes[ off + i ] ); | |
1697 | } // end for: each byte written | |
1698 | ||
1699 | } // end write | |
1700 | ||
1701 | ||
1702 | ||
1703 | /** | |
1704 | * Method added by PHIL. [Thanks, PHIL. -Rob] | |
1705 | * This pads the buffer without closing the stream. | |
1706 | */ | |
1707 | public void flushBase64() throws java.io.IOException | |
1708 | { | |
1709 | if( position > 0 ) | |
1710 | { | |
1711 | if( encode ) | |
1712 | { | |
1713 | out.write( encode3to4( b4, buffer, position, options ) ); | |
1714 | position = 0; | |
1715 | } // end if: encoding | |
1716 | else | |
1717 | { | |
1718 | throw new java.io.IOException( "Base64 input not properly padded." ); | |
1719 | } // end else: decoding | |
1720 | } // end if: buffer partially full | |
1721 | ||
1722 | } // end flush | |
1723 | ||
1724 | ||
1725 | /** | |
1726 | * Flushes and closes (I think, in the superclass) the stream. | |
1727 | * | |
1728 | * @since 1.3 | |
1729 | */ | |
1730 | public void close() throws java.io.IOException | |
1731 | { | |
1732 | // 1. Ensure that pending characters are written | |
1733 | flushBase64(); | |
1734 | ||
1735 | // 2. Actually close the stream | |
1736 | // Base class both flushes and closes. | |
1737 | super.close(); | |
1738 | ||
1739 | buffer = null; | |
1740 | out = null; | |
1741 | } // end close | |
1742 | ||
1743 | ||
1744 | ||
1745 | /** | |
1746 | * Suspends encoding of the stream. | |
1747 | * May be helpful if you need to embed a piece of | |
1748 | * base640-encoded data in a stream. | |
1749 | * | |
1750 | * @since 1.5.1 | |
1751 | */ | |
1752 | public void suspendEncoding() throws java.io.IOException | |
1753 | { | |
1754 | flushBase64(); | |
1755 | this.suspendEncoding = true; | |
1756 | } // end suspendEncoding | |
1757 | ||
1758 | ||
1759 | /** | |
1760 | * Resumes encoding of the stream. | |
1761 | * May be helpful if you need to embed a piece of | |
1762 | * base640-encoded data in a stream. | |
1763 | * | |
1764 | * @since 1.5.1 | |
1765 | */ | |
1766 | public void resumeEncoding() | |
1767 | { | |
1768 | this.suspendEncoding = false; | |
1769 | } // end resumeEncoding | |
1770 | ||
1771 | ||
1772 | ||
1773 | } // end inner class OutputStream | |
1774 | ||
1775 | ||
1776 | } // end class Base64 |