1 package cx.fbn.nevernote.utilities;
\r
5 * <p>Encodes and decodes to and from Base64 notation.</p>
\r
6 * <p>Homepage: <a href="http://iharder.net/base64">http://iharder.net/base64</a>.</p>
\r
10 * <code>String encoded = Base64.encode( myByteArray );</code>
\r
12 * <code>byte[] myByteArray = Base64.decode( encoded );</code>
\r
14 * <p>The <tt>options</tt> parameter, which appears in a few places, is used to pass
\r
15 * several pieces of information to the encoder. In the "higher level" methods such as
\r
16 * encodeBytes( bytes, options ) the options parameter can be used to indicate such
\r
17 * things as first gzipping the bytes before encoding them, not inserting linefeeds,
\r
18 * and encoding using the URL-safe and Ordered dialects.</p>
\r
20 * <p>Note, according to <a href="http://www.faqs.org/rfcs/rfc3548.html">RFC3548</a>,
\r
21 * Section 2.1, implementations should not add line feeds unless explicitly told
\r
22 * to do so. I've got Base64 set to this behavior now, although earlier versions
\r
23 * broke lines by default.</p>
\r
25 * <p>The constants defined in Base64 can be OR-ed together to combine options, so you
\r
26 * might make a call like this:</p>
\r
28 * <code>String encoded = Base64.encodeBytes( mybytes, Base64.GZIP | Base64.DO_BREAK_LINES );</code>
\r
29 * <p>to compress the data before encoding it and then making the output have newline characters.</p>
\r
31 * <code>String encoded = Base64.encodeBytes( crazyString.getBytes() );</code>
\r
39 * <li>v2.3.4 - Fixed bug when working with gzipped streams whereby flushing
\r
40 * the Base64.OutputStream closed the Base64 encoding (by padding with equals
\r
41 * signs) too soon. Also added an option to suppress the automatic decoding
\r
42 * of gzipped streams. Also added experimental support for specifying a
\r
43 * class loader when using the
\r
44 * {@link #decodeToObject(java.lang.String, int, java.lang.ClassLoader)}
\r
46 * <li>v2.3.3 - Changed default char encoding to US-ASCII which reduces the internal Java
\r
47 * footprint with its CharEncoders and so forth. Fixed some javadocs that were
\r
48 * inconsistent. Removed imports and specified things like java.io.IOException
\r
49 * explicitly inline.</li>
\r
50 * <li>v2.3.2 - Reduced memory footprint! Finally refined the "guessing" of how big the
\r
51 * final encoded data will be so that the code doesn't have to create two output
\r
52 * arrays: an oversized initial one and then a final, exact-sized one. Big win
\r
53 * when using the {@link #encodeBytesToBytes(byte[])} family of methods (and not
\r
54 * using the gzip options which uses a different mechanism with streams and stuff).</li>
\r
55 * <li>v2.3.1 - Added {@link #encodeBytesToBytes(byte[], int, int, int)} and some
\r
56 * similar helper methods to be more efficient with memory by not returning a
\r
57 * String but just a byte array.</li>
\r
58 * <li>v2.3 - <strong>This is not a drop-in replacement!</strong> This is two years of comments
\r
59 * and bug fixes queued up and finally executed. Thanks to everyone who sent
\r
60 * me stuff, and I'm sorry I wasn't able to distribute your fixes to everyone else.
\r
61 * Much bad coding was cleaned up including throwing exceptions where necessary
\r
62 * instead of returning null values or something similar. Here are some changes
\r
63 * that may affect you:
\r
65 * <li><em>Does not break lines, by default.</em> This is to keep in compliance with
\r
66 * <a href="http://www.faqs.org/rfcs/rfc3548.html">RFC3548</a>.</li>
\r
67 * <li><em>Throws exceptions instead of returning null values.</em> Because some operations
\r
68 * (especially those that may permit the GZIP option) use IO streams, there
\r
69 * is a possiblity of an java.io.IOException being thrown. After some discussion and
\r
70 * thought, I've changed the behavior of the methods to throw java.io.IOExceptions
\r
71 * rather than return null if ever there's an error. I think this is more
\r
72 * appropriate, though it will require some changes to your code. Sorry,
\r
73 * it should have been done this way to begin with.</li>
\r
74 * <li><em>Removed all references to System.out, System.err, and the like.</em>
\r
75 * Shame on me. All I can say is sorry they were ever there.</li>
\r
76 * <li><em>Throws NullPointerExceptions and IllegalArgumentExceptions</em> as needed
\r
77 * such as when passed arrays are null or offsets are invalid.</li>
\r
78 * <li>Cleaned up as much javadoc as I could to avoid any javadoc warnings.
\r
79 * This was especially annoying before for people who were thorough in their
\r
80 * own projects and then had gobs of javadoc warnings on this file.</li>
\r
82 * <li>v2.2.1 - Fixed bug using URL_SAFE and ORDERED encodings. Fixed bug
\r
83 * when using very small files (~< 40 bytes).</li>
\r
84 * <li>v2.2 - Added some helper methods for encoding/decoding directly from
\r
85 * one file to the next. Also added a main() method to support command line
\r
86 * encoding/decoding from one file to the next. Also added these Base64 dialects:
\r
88 * <li>The default is RFC3548 format.</li>
\r
89 * <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.URLSAFE_FORMAT) generates
\r
90 * URL and file name friendly format as described in Section 4 of RFC3548.
\r
91 * http://www.faqs.org/rfcs/rfc3548.html</li>
\r
92 * <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.ORDERED_FORMAT) generates
\r
93 * URL and file name friendly format that preserves lexical ordering as described
\r
94 * in http://www.faqs.org/qa/rfcc-1940.html</li>
\r
96 * Special thanks to Jim Kellerman at <a href="http://www.powerset.com/">http://www.powerset.com/</a>
\r
97 * for contributing the new Base64 dialects.
\r
100 * <li>v2.1 - Cleaned up javadoc comments and unused variables and methods. Added
\r
101 * some convenience methods for reading and writing to and from files.</li>
\r
102 * <li>v2.0.2 - Now specifies UTF-8 encoding in places where the code fails on systems
\r
103 * with other encodings (like EBCDIC).</li>
\r
104 * <li>v2.0.1 - Fixed an error when decoding a single byte, that is, when the
\r
105 * encoded data was a single byte.</li>
\r
106 * <li>v2.0 - I got rid of methods that used booleans to set options.
\r
107 * Now everything is more consolidated and cleaner. The code now detects
\r
108 * when data that's being decoded is gzip-compressed and will decompress it
\r
109 * automatically. Generally things are cleaner. You'll probably have to
\r
110 * change some method calls that you were making to support the new
\r
111 * options format (<tt>int</tt>s that you "OR" together).</li>
\r
112 * <li>v1.5.1 - Fixed bug when decompressing and decoding to a
\r
113 * byte[] using <tt>decode( String s, boolean gzipCompressed )</tt>.
\r
114 * Added the ability to "suspend" encoding in the Output Stream so
\r
115 * you can turn on and off the encoding if you need to embed base64
\r
116 * data in an otherwise "normal" stream (like an XML file).</li>
\r
117 * <li>v1.5 - Output stream pases on flush() command but doesn't do anything itself.
\r
118 * This helps when using GZIP streams.
\r
119 * Added the ability to GZip-compress objects before encoding them.</li>
\r
120 * <li>v1.4 - Added helper methods to read/write files.</li>
\r
121 * <li>v1.3.6 - Fixed OutputStream.flush() so that 'position' is reset.</li>
\r
122 * <li>v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in input stream
\r
123 * where last buffer being read, if not completely full, was not returned.</li>
\r
124 * <li>v1.3.4 - Fixed when "improperly padded stream" error was thrown at the wrong time.</li>
\r
125 * <li>v1.3.3 - Fixed I/O streams which were totally messed up.</li>
\r
129 * I am placing this code in the Public Domain. Do with it as you will.
\r
130 * This software comes with no guarantees or warranties but with
\r
131 * plenty of well-wishing instead!
\r
132 * Please visit <a href="http://iharder.net/base64">http://iharder.net/base64</a>
\r
133 * periodically to check for updates or to contribute improvements.
\r
136 * @author Robert Harder
\r
137 * @author rob@iharder.net
\r
140 public class Base64
\r
143 /* ******** P U B L I C F I E L D S ******** */
\r
146 /** No options specified. Value is zero. */
\r
147 public final static int NO_OPTIONS = 0;
\r
149 /** Specify encoding in first bit. Value is one. */
\r
150 public final static int ENCODE = 1;
\r
153 /** Specify decoding in first bit. Value is zero. */
\r
154 public final static int DECODE = 0;
\r
157 /** Specify that data should be gzip-compressed in second bit. Value is two. */
\r
158 public final static int GZIP = 2;
\r
160 /** Specify that gzipped data should <em>not</em> be automatically gunzipped. */
\r
161 public final static int DONT_GUNZIP = 4;
\r
164 /** Do break lines when encoding. Value is 8. */
\r
165 public final static int DO_BREAK_LINES = 8;
\r
168 * Encode using Base64-like encoding that is URL- and Filename-safe as described
\r
169 * in Section 4 of RFC3548:
\r
170 * <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>.
\r
171 * It is important to note that data encoded this way is <em>not</em> officially valid Base64,
\r
172 * or at the very least should not be called Base64 without also specifying that is
\r
173 * was encoded using the URL- and Filename-safe dialect.
\r
175 public final static int URL_SAFE = 16;
\r
179 * Encode using the special "ordered" dialect of Base64 described here:
\r
180 * <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>.
\r
182 public final static int ORDERED = 32;
\r
185 /* ******** P R I V A T E F I E L D S ******** */
\r
188 /** Maximum line length (76) of Base64 output. */
\r
189 private final static int MAX_LINE_LENGTH = 76;
\r
192 /** The equals sign (=) as a byte. */
\r
193 private final static byte EQUALS_SIGN = (byte)'=';
\r
196 /** The new line character (\n) as a byte. */
\r
197 private final static byte NEW_LINE = (byte)'\n';
\r
200 /** Preferred encoding. */
\r
201 private final static String PREFERRED_ENCODING = "US-ASCII";
\r
204 private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding
\r
205 private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding
\r
208 /* ******** S T A N D A R D B A S E 6 4 A L P H A B E T ******** */
\r
210 /** The 64 valid Base64 values. */
\r
211 /* Host platform me be something funny like EBCDIC, so we hardcode these values. */
\r
212 private final static byte[] _STANDARD_ALPHABET = {
\r
213 (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
\r
214 (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
\r
215 (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
\r
216 (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
\r
217 (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
\r
218 (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
\r
219 (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
\r
220 (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z',
\r
221 (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5',
\r
222 (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/'
\r
227 * Translates a Base64 value to either its 6-bit reconstruction value
\r
228 * or a negative number indicating some other meaning.
\r
230 private final static byte[] _STANDARD_DECODABET = {
\r
231 -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8
\r
232 -5,-5, // Whitespace: Tab and Linefeed
\r
233 -9,-9, // Decimal 11 - 12
\r
234 -5, // Whitespace: Carriage Return
\r
235 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26
\r
236 -9,-9,-9,-9,-9, // Decimal 27 - 31
\r
237 -5, // Whitespace: Space
\r
238 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42
\r
239 62, // Plus sign at decimal 43
\r
240 -9,-9,-9, // Decimal 44 - 46
\r
241 63, // Slash at decimal 47
\r
242 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine
\r
243 -9,-9,-9, // Decimal 58 - 60
\r
244 -1, // Equals sign at decimal 61
\r
245 -9,-9,-9, // Decimal 62 - 64
\r
246 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N'
\r
247 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z'
\r
248 -9,-9,-9,-9,-9,-9, // Decimal 91 - 96
\r
249 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm'
\r
250 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z'
\r
251 -9,-9,-9,-9 // Decimal 123 - 126
\r
252 /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139
\r
253 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
\r
254 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
\r
255 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
\r
256 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
\r
257 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
\r
258 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
\r
259 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
\r
260 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
\r
261 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */
\r
265 /* ******** U R L S A F E B A S E 6 4 A L P H A B E T ******** */
\r
268 * Used in the URL- and Filename-safe dialect described in Section 4 of RFC3548:
\r
269 * <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>.
\r
270 * Notice that the last two bytes become "hyphen" and "underscore" instead of "plus" and "slash."
\r
272 private final static byte[] _URL_SAFE_ALPHABET = {
\r
273 (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
\r
274 (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
\r
275 (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
\r
276 (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
\r
277 (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
\r
278 (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
\r
279 (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
\r
280 (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z',
\r
281 (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5',
\r
282 (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'-', (byte)'_'
\r
286 * Used in decoding URL- and Filename-safe dialects of Base64.
\r
288 private final static byte[] _URL_SAFE_DECODABET = {
\r
289 -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8
\r
290 -5,-5, // Whitespace: Tab and Linefeed
\r
291 -9,-9, // Decimal 11 - 12
\r
292 -5, // Whitespace: Carriage Return
\r
293 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26
\r
294 -9,-9,-9,-9,-9, // Decimal 27 - 31
\r
295 -5, // Whitespace: Space
\r
296 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42
\r
297 -9, // Plus sign at decimal 43
\r
299 62, // Minus sign at decimal 45
\r
301 -9, // Slash at decimal 47
\r
302 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine
\r
303 -9,-9,-9, // Decimal 58 - 60
\r
304 -1, // Equals sign at decimal 61
\r
305 -9,-9,-9, // Decimal 62 - 64
\r
306 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N'
\r
307 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z'
\r
308 -9,-9,-9,-9, // Decimal 91 - 94
\r
309 63, // Underscore at decimal 95
\r
311 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm'
\r
312 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z'
\r
313 -9,-9,-9,-9 // Decimal 123 - 126
\r
314 /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139
\r
315 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
\r
316 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
\r
317 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
\r
318 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
\r
319 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
\r
320 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
\r
321 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
\r
322 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
\r
323 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */
\r
328 /* ******** O R D E R E D B A S E 6 4 A L P H A B E T ******** */
\r
331 * I don't get the point of this technique, but someone requested it,
\r
332 * and it is described here:
\r
333 * <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>.
\r
335 private final static byte[] _ORDERED_ALPHABET = {
\r
337 (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4',
\r
338 (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9',
\r
339 (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
\r
340 (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
\r
341 (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
\r
342 (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
\r
344 (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
\r
345 (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
\r
346 (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
\r
347 (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z'
\r
351 * Used in decoding the "ordered" dialect of Base64.
\r
353 private final static byte[] _ORDERED_DECODABET = {
\r
354 -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8
\r
355 -5,-5, // Whitespace: Tab and Linefeed
\r
356 -9,-9, // Decimal 11 - 12
\r
357 -5, // Whitespace: Carriage Return
\r
358 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26
\r
359 -9,-9,-9,-9,-9, // Decimal 27 - 31
\r
360 -5, // Whitespace: Space
\r
361 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42
\r
362 -9, // Plus sign at decimal 43
\r
364 0, // Minus sign at decimal 45
\r
366 -9, // Slash at decimal 47
\r
367 1,2,3,4,5,6,7,8,9,10, // Numbers zero through nine
\r
368 -9,-9,-9, // Decimal 58 - 60
\r
369 -1, // Equals sign at decimal 61
\r
370 -9,-9,-9, // Decimal 62 - 64
\r
371 11,12,13,14,15,16,17,18,19,20,21,22,23, // Letters 'A' through 'M'
\r
372 24,25,26,27,28,29,30,31,32,33,34,35,36, // Letters 'N' through 'Z'
\r
373 -9,-9,-9,-9, // Decimal 91 - 94
\r
374 37, // Underscore at decimal 95
\r
376 38,39,40,41,42,43,44,45,46,47,48,49,50, // Letters 'a' through 'm'
\r
377 51,52,53,54,55,56,57,58,59,60,61,62,63, // Letters 'n' through 'z'
\r
378 -9,-9,-9,-9 // Decimal 123 - 126
\r
379 /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139
\r
380 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
\r
381 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
\r
382 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
\r
383 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
\r
384 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
\r
385 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
\r
386 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
\r
387 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
\r
388 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */
\r
392 /* ******** D E T E R M I N E W H I C H A L H A B E T ******** */
\r
396 * Returns one of the _SOMETHING_ALPHABET byte arrays depending on
\r
397 * the options specified.
\r
398 * It's possible, though silly, to specify ORDERED <b>and</b> URLSAFE
\r
399 * in which case one of them will be picked, though there is
\r
400 * no guarantee as to which one will be picked.
\r
402 private final static byte[] getAlphabet( int options ) {
\r
403 if ((options & URL_SAFE) == URL_SAFE) {
\r
404 return _URL_SAFE_ALPHABET;
\r
405 } else if ((options & ORDERED) == ORDERED) {
\r
406 return _ORDERED_ALPHABET;
\r
408 return _STANDARD_ALPHABET;
\r
410 } // end getAlphabet
\r
414 * Returns one of the _SOMETHING_DECODABET byte arrays depending on
\r
415 * the options specified.
\r
416 * It's possible, though silly, to specify ORDERED and URL_SAFE
\r
417 * in which case one of them will be picked, though there is
\r
418 * no guarantee as to which one will be picked.
\r
420 private final static byte[] getDecodabet( int options ) {
\r
421 if( (options & URL_SAFE) == URL_SAFE) {
\r
422 return _URL_SAFE_DECODABET;
\r
423 } else if ((options & ORDERED) == ORDERED) {
\r
424 return _ORDERED_DECODABET;
\r
426 return _STANDARD_DECODABET;
\r
428 } // end getAlphabet
\r
432 /** Defeats instantiation. */
\r
438 /* ******** E N C O D I N G M E T H O D S ******** */
\r
442 * Encodes up to the first three bytes of array <var>threeBytes</var>
\r
443 * and returns a four-byte array in Base64 notation.
\r
444 * The actual number of significant bytes in your array is
\r
445 * given by <var>numSigBytes</var>.
\r
446 * The array <var>threeBytes</var> needs only be as big as
\r
447 * <var>numSigBytes</var>.
\r
448 * Code can reuse a byte array by passing a four-byte array as <var>b4</var>.
\r
450 * @param b4 A reusable byte array to reduce array instantiation
\r
451 * @param threeBytes the array to convert
\r
452 * @param numSigBytes the number of significant bytes in your array
\r
453 * @return four byte array in Base64 notation.
\r
456 private static byte[] encode3to4( byte[] b4, byte[] threeBytes, int numSigBytes, int options ) {
\r
457 encode3to4( threeBytes, 0, numSigBytes, b4, 0, options );
\r
459 } // end encode3to4
\r
463 * <p>Encodes up to three bytes of the array <var>source</var>
\r
464 * and writes the resulting four Base64 bytes to <var>destination</var>.
\r
465 * The source and destination arrays can be manipulated
\r
466 * anywhere along their length by specifying
\r
467 * <var>srcOffset</var> and <var>destOffset</var>.
\r
468 * This method does not check to make sure your arrays
\r
469 * are large enough to accomodate <var>srcOffset</var> + 3 for
\r
470 * the <var>source</var> array or <var>destOffset</var> + 4 for
\r
471 * the <var>destination</var> array.
\r
472 * The actual number of significant bytes in your array is
\r
473 * given by <var>numSigBytes</var>.</p>
\r
474 * <p>This is the lowest level of the encoding methods with
\r
475 * all possible parameters.</p>
\r
477 * @param source the array to convert
\r
478 * @param srcOffset the index where conversion begins
\r
479 * @param numSigBytes the number of significant bytes in your array
\r
480 * @param destination the array to hold the conversion
\r
481 * @param destOffset the index where output will be put
\r
482 * @return the <var>destination</var> array
\r
485 private static byte[] encode3to4(
\r
486 byte[] source, int srcOffset, int numSigBytes,
\r
487 byte[] destination, int destOffset, int options ) {
\r
489 byte[] ALPHABET = getAlphabet( options );
\r
492 // 01234567890123456789012345678901 Bit position
\r
493 // --------000000001111111122222222 Array position from threeBytes
\r
494 // --------| || || || | Six bit groups to index ALPHABET
\r
495 // >>18 >>12 >> 6 >> 0 Right shift necessary
\r
496 // 0x3f 0x3f 0x3f Additional AND
\r
498 // Create buffer with zero-padding if there are only one or two
\r
499 // significant bytes passed in the array.
\r
500 // We have to shift left 24 in order to flush out the 1's that appear
\r
501 // when Java treats a value as negative that is cast from a byte to an int.
\r
502 int inBuff = ( numSigBytes > 0 ? ((source[ srcOffset ] << 24) >>> 8) : 0 )
\r
503 | ( numSigBytes > 1 ? ((source[ srcOffset + 1 ] << 24) >>> 16) : 0 )
\r
504 | ( numSigBytes > 2 ? ((source[ srcOffset + 2 ] << 24) >>> 24) : 0 );
\r
506 switch( numSigBytes )
\r
509 destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
\r
510 destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
\r
511 destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ];
\r
512 destination[ destOffset + 3 ] = ALPHABET[ (inBuff ) & 0x3f ];
\r
513 return destination;
\r
516 destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
\r
517 destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
\r
518 destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ];
\r
519 destination[ destOffset + 3 ] = EQUALS_SIGN;
\r
520 return destination;
\r
523 destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
\r
524 destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
\r
525 destination[ destOffset + 2 ] = EQUALS_SIGN;
\r
526 destination[ destOffset + 3 ] = EQUALS_SIGN;
\r
527 return destination;
\r
530 return destination;
\r
532 } // end encode3to4
\r
537 * Performs Base64 encoding on the <code>raw</code> ByteBuffer,
\r
538 * writing it to the <code>encoded</code> ByteBuffer.
\r
539 * This is an experimental feature. Currently it does not
\r
540 * pass along any options (such as {@link #DO_BREAK_LINES}
\r
541 * or {@link #GZIP}.
\r
543 * @param raw input buffer
\r
544 * @param encoded output buffer
\r
547 public static void encode( java.nio.ByteBuffer raw, java.nio.ByteBuffer encoded ){
\r
548 byte[] raw3 = new byte[3];
\r
549 byte[] enc4 = new byte[4];
\r
551 while( raw.hasRemaining() ){
\r
552 int rem = Math.min(3,raw.remaining());
\r
553 raw.get(raw3,0,rem);
\r
554 Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS );
\r
556 } // end input remaining
\r
561 * Performs Base64 encoding on the <code>raw</code> ByteBuffer,
\r
562 * writing it to the <code>encoded</code> CharBuffer.
\r
563 * This is an experimental feature. Currently it does not
\r
564 * pass along any options (such as {@link #DO_BREAK_LINES}
\r
565 * or {@link #GZIP}.
\r
567 * @param raw input buffer
\r
568 * @param encoded output buffer
\r
571 public static void encode( java.nio.ByteBuffer raw, java.nio.CharBuffer encoded ){
\r
572 byte[] raw3 = new byte[3];
\r
573 byte[] enc4 = new byte[4];
\r
575 while( raw.hasRemaining() ){
\r
576 int rem = Math.min(3,raw.remaining());
\r
577 raw.get(raw3,0,rem);
\r
578 Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS );
\r
579 for( int i = 0; i < 4; i++ ){
\r
580 encoded.put( (char)(enc4[i] & 0xFF) );
\r
582 } // end input remaining
\r
589 * Serializes an object and returns the Base64-encoded
\r
590 * version of that serialized object.
\r
592 * <p>As of v 2.3, if the object
\r
593 * cannot be serialized or there is another error,
\r
594 * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
\r
595 * In earlier versions, it just returned a null value, but
\r
596 * in retrospect that's a pretty poor way to handle it.</p>
\r
598 * The object is not GZip-compressed before being encoded.
\r
600 * @param serializableObject The object to encode
\r
601 * @return The Base64-encoded object
\r
602 * @throws java.io.IOException if there is an error
\r
603 * @throws NullPointerException if serializedObject is null
\r
606 public static String encodeObject( java.io.Serializable serializableObject )
\r
607 throws java.io.IOException {
\r
608 return encodeObject( serializableObject, NO_OPTIONS );
\r
609 } // end encodeObject
\r
614 * Serializes an object and returns the Base64-encoded
\r
615 * version of that serialized object.
\r
617 * <p>As of v 2.3, if the object
\r
618 * cannot be serialized or there is another error,
\r
619 * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
\r
620 * In earlier versions, it just returned a null value, but
\r
621 * in retrospect that's a pretty poor way to handle it.</p>
\r
623 * The object is not GZip-compressed before being encoded.
\r
625 * Example options:<pre>
\r
626 * GZIP: gzip-compresses object before encoding it.
\r
627 * DO_BREAK_LINES: break lines at 76 characters
\r
630 * Example: <code>encodeObject( myObj, Base64.GZIP )</code> or
\r
632 * Example: <code>encodeObject( myObj, Base64.GZIP | Base64.DO_BREAK_LINES )</code>
\r
634 * @param serializableObject The object to encode
\r
635 * @param options Specified options
\r
636 * @return The Base64-encoded object
\r
638 * @see Base64#DO_BREAK_LINES
\r
639 * @throws java.io.IOException if there is an error
\r
642 public static String encodeObject( java.io.Serializable serializableObject, int options )
\r
643 throws java.io.IOException {
\r
645 if( serializableObject == null ){
\r
646 throw new NullPointerException( "Cannot serialize a null object." );
\r
650 java.io.ByteArrayOutputStream baos = null;
\r
651 java.io.OutputStream b64os = null;
\r
652 java.util.zip.GZIPOutputStream gzos = null;
\r
653 java.io.ObjectOutputStream oos = null;
\r
657 // ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream
\r
658 baos = new java.io.ByteArrayOutputStream();
\r
659 b64os = new Base64.OutputStream( baos, ENCODE | options );
\r
660 if( (options & GZIP) != 0 ){
\r
662 gzos = new java.util.zip.GZIPOutputStream(b64os);
\r
663 oos = new java.io.ObjectOutputStream( gzos );
\r
666 oos = new java.io.ObjectOutputStream( b64os );
\r
668 oos.writeObject( serializableObject );
\r
670 catch( java.io.IOException e ) {
\r
671 // Catch it and then throw it immediately so that
\r
672 // the finally{} block is called for cleanup.
\r
676 try{ oos.close(); } catch( Exception e ){}
\r
677 try{ gzos.close(); } catch( Exception e ){}
\r
678 try{ b64os.close(); } catch( Exception e ){}
\r
679 try{ baos.close(); } catch( Exception e ){}
\r
682 // Return value according to relevant encoding.
\r
684 return new String( baos.toByteArray(), PREFERRED_ENCODING );
\r
686 catch (java.io.UnsupportedEncodingException uue){
\r
687 // Fall back to some Java default
\r
688 return new String( baos.toByteArray() );
\r
696 * Encodes a byte array into Base64 notation.
\r
697 * Does not GZip-compress data.
\r
699 * @param source The data to convert
\r
700 * @return The data in Base64-encoded form
\r
701 * @throws NullPointerException if source array is null
\r
704 public static String encodeBytes( byte[] source ) {
\r
705 // Since we're not going to have the GZIP encoding turned on,
\r
706 // we're not going to have an java.io.IOException thrown, so
\r
707 // we should not force the user to have to catch it.
\r
708 String encoded = null;
\r
710 encoded = encodeBytes(source, 0, source.length, NO_OPTIONS);
\r
711 } catch (java.io.IOException ex) {
\r
712 assert false : ex.getMessage();
\r
714 assert encoded != null;
\r
716 } // end encodeBytes
\r
721 * Encodes a byte array into Base64 notation.
\r
723 * Example options:<pre>
\r
724 * GZIP: gzip-compresses object before encoding it.
\r
725 * DO_BREAK_LINES: break lines at 76 characters
\r
726 * <i>Note: Technically, this makes your encoding non-compliant.</i>
\r
729 * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
\r
731 * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES )</code>
\r
734 * <p>As of v 2.3, if there is an error with the GZIP stream,
\r
735 * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
\r
736 * In earlier versions, it just returned a null value, but
\r
737 * in retrospect that's a pretty poor way to handle it.</p>
\r
740 * @param source The data to convert
\r
741 * @param options Specified options
\r
742 * @return The Base64-encoded data as a String
\r
744 * @see Base64#DO_BREAK_LINES
\r
745 * @throws java.io.IOException if there is an error
\r
746 * @throws NullPointerException if source array is null
\r
749 public static String encodeBytes( byte[] source, int options ) throws java.io.IOException {
\r
750 return encodeBytes( source, 0, source.length, options );
\r
751 } // end encodeBytes
\r
755 * Encodes a byte array into Base64 notation.
\r
756 * Does not GZip-compress data.
\r
758 * <p>As of v 2.3, if there is an error,
\r
759 * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
\r
760 * In earlier versions, it just returned a null value, but
\r
761 * in retrospect that's a pretty poor way to handle it.</p>
\r
764 * @param source The data to convert
\r
765 * @param off Offset in array where conversion should begin
\r
766 * @param len Length of data to convert
\r
767 * @return The Base64-encoded data as a String
\r
768 * @throws NullPointerException if source array is null
\r
769 * @throws IllegalArgumentException if source array, offset, or length are invalid
\r
772 public static String encodeBytes( byte[] source, int off, int len ) {
\r
773 // Since we're not going to have the GZIP encoding turned on,
\r
774 // we're not going to have an java.io.IOException thrown, so
\r
775 // we should not force the user to have to catch it.
\r
776 String encoded = null;
\r
778 encoded = encodeBytes( source, off, len, NO_OPTIONS );
\r
779 } catch (java.io.IOException ex) {
\r
780 assert false : ex.getMessage();
\r
782 assert encoded != null;
\r
784 } // end encodeBytes
\r
789 * Encodes a byte array into Base64 notation.
\r
791 * Example options:<pre>
\r
792 * GZIP: gzip-compresses object before encoding it.
\r
793 * DO_BREAK_LINES: break lines at 76 characters
\r
794 * <i>Note: Technically, this makes your encoding non-compliant.</i>
\r
797 * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
\r
799 * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES )</code>
\r
802 * <p>As of v 2.3, if there is an error with the GZIP stream,
\r
803 * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
\r
804 * In earlier versions, it just returned a null value, but
\r
805 * in retrospect that's a pretty poor way to handle it.</p>
\r
808 * @param source The data to convert
\r
809 * @param off Offset in array where conversion should begin
\r
810 * @param len Length of data to convert
\r
811 * @param options Specified options
\r
812 * @return The Base64-encoded data as a String
\r
814 * @see Base64#DO_BREAK_LINES
\r
815 * @throws java.io.IOException if there is an error
\r
816 * @throws NullPointerException if source array is null
\r
817 * @throws IllegalArgumentException if source array, offset, or length are invalid
\r
820 public static String encodeBytes( byte[] source, int off, int len, int options ) throws java.io.IOException {
\r
821 byte[] encoded = encodeBytesToBytes( source, off, len, options );
\r
823 // Return value according to relevant encoding.
\r
825 return new String( encoded, PREFERRED_ENCODING );
\r
827 catch (java.io.UnsupportedEncodingException uue) {
\r
828 return new String( encoded );
\r
831 } // end encodeBytes
\r
837 * Similar to {@link #encodeBytes(byte[])} but returns
\r
838 * a byte array instead of instantiating a String. This is more efficient
\r
839 * if you're working with I/O streams and have large data sets to encode.
\r
842 * @param source The data to convert
\r
843 * @return The Base64-encoded data as a byte[] (of ASCII characters)
\r
844 * @throws NullPointerException if source array is null
\r
847 public static byte[] encodeBytesToBytes( byte[] source ) {
\r
848 byte[] encoded = null;
\r
850 encoded = encodeBytesToBytes( source, 0, source.length, Base64.NO_OPTIONS );
\r
851 } catch( java.io.IOException ex ) {
\r
852 assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage();
\r
859 * Similar to {@link #encodeBytes(byte[], int, int, int)} but returns
\r
860 * a byte array instead of instantiating a String. This is more efficient
\r
861 * if you're working with I/O streams and have large data sets to encode.
\r
864 * @param source The data to convert
\r
865 * @param off Offset in array where conversion should begin
\r
866 * @param len Length of data to convert
\r
867 * @param options Specified options
\r
868 * @return The Base64-encoded data as a String
\r
870 * @see Base64#DO_BREAK_LINES
\r
871 * @throws java.io.IOException if there is an error
\r
872 * @throws NullPointerException if source array is null
\r
873 * @throws IllegalArgumentException if source array, offset, or length are invalid
\r
876 public static byte[] encodeBytesToBytes( byte[] source, int off, int len, int options ) throws java.io.IOException {
\r
878 if( source == null ){
\r
879 throw new NullPointerException( "Cannot serialize a null array." );
\r
883 throw new IllegalArgumentException( "Cannot have negative offset: " + off );
\r
884 } // end if: off < 0
\r
887 throw new IllegalArgumentException( "Cannot have length offset: " + len );
\r
888 } // end if: len < 0
\r
890 if( off + len > source.length ){
\r
891 throw new IllegalArgumentException(
\r
892 String.format( "Cannot have offset of %d and length of %d with array of length %d", off,len,source.length));
\r
893 } // end if: off < 0
\r
898 if( (options & GZIP) != 0 ) {
\r
899 java.io.ByteArrayOutputStream baos = null;
\r
900 java.util.zip.GZIPOutputStream gzos = null;
\r
901 Base64.OutputStream b64os = null;
\r
904 // GZip -> Base64 -> ByteArray
\r
905 baos = new java.io.ByteArrayOutputStream();
\r
906 b64os = new Base64.OutputStream( baos, ENCODE | options );
\r
907 gzos = new java.util.zip.GZIPOutputStream( b64os );
\r
909 gzos.write( source, off, len );
\r
912 catch( java.io.IOException e ) {
\r
913 // Catch it and then throw it immediately so that
\r
914 // the finally{} block is called for cleanup.
\r
918 try{ gzos.close(); } catch( Exception e ){}
\r
919 try{ b64os.close(); } catch( Exception e ){}
\r
920 try{ baos.close(); } catch( Exception e ){}
\r
923 return baos.toByteArray();
\r
924 } // end if: compress
\r
926 // Else, don't compress. Better not to use streams at all then.
\r
928 boolean breakLines = (options & DO_BREAK_LINES) > 0;
\r
930 //int len43 = len * 4 / 3;
\r
931 //byte[] outBuff = new byte[ ( len43 ) // Main 4:3
\r
932 // + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding
\r
933 // + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines
\r
934 // Try to determine more precisely how big the array needs to be.
\r
935 // If we get it right, we don't have to do an array copy, and
\r
936 // we save a bunch of memory.
\r
937 int encLen = ( len / 3 ) * 4 + ( len % 3 > 0 ? 4 : 0 ); // Bytes needed for actual encoding
\r
939 encLen += encLen / MAX_LINE_LENGTH; // Plus extra newline characters
\r
941 byte[] outBuff = new byte[ encLen ];
\r
946 int len2 = len - 2;
\r
947 int lineLength = 0;
\r
948 for( ; d < len2; d+=3, e+=4 ) {
\r
949 encode3to4( source, d+off, 3, outBuff, e, options );
\r
952 if( breakLines && lineLength >= MAX_LINE_LENGTH )
\r
954 outBuff[e+4] = NEW_LINE;
\r
957 } // end if: end of line
\r
958 } // en dfor: each piece of array
\r
961 encode3to4( source, d+off, len - d, outBuff, e, options );
\r
963 } // end if: some padding needed
\r
966 // Only resize array if we didn't guess it right.
\r
967 if( e < outBuff.length - 1 ){
\r
968 byte[] finalOut = new byte[e];
\r
969 System.arraycopy(outBuff,0, finalOut,0,e);
\r
970 //System.err.println("Having to resize array from " + outBuff.length + " to " + e );
\r
973 //System.err.println("No need to resize array.");
\r
977 } // end else: don't compress
\r
979 } // end encodeBytesToBytes
\r
985 /* ******** D E C O D I N G M E T H O D S ******** */
\r
989 * Decodes four bytes from array <var>source</var>
\r
990 * and writes the resulting bytes (up to three of them)
\r
991 * to <var>destination</var>.
\r
992 * The source and destination arrays can be manipulated
\r
993 * anywhere along their length by specifying
\r
994 * <var>srcOffset</var> and <var>destOffset</var>.
\r
995 * This method does not check to make sure your arrays
\r
996 * are large enough to accomodate <var>srcOffset</var> + 4 for
\r
997 * the <var>source</var> array or <var>destOffset</var> + 3 for
\r
998 * the <var>destination</var> array.
\r
999 * This method returns the actual number of bytes that
\r
1000 * were converted from the Base64 encoding.
\r
1001 * <p>This is the lowest level of the decoding methods with
\r
1002 * all possible parameters.</p>
\r
1005 * @param source the array to convert
\r
1006 * @param srcOffset the index where conversion begins
\r
1007 * @param destination the array to hold the conversion
\r
1008 * @param destOffset the index where output will be put
\r
1009 * @param options alphabet type is pulled from this (standard, url-safe, ordered)
\r
1010 * @return the number of decoded bytes converted
\r
1011 * @throws NullPointerException if source or destination arrays are null
\r
1012 * @throws IllegalArgumentException if srcOffset or destOffset are invalid
\r
1013 * or there is not enough room in the array.
\r
1016 private static int decode4to3(
\r
1017 byte[] source, int srcOffset,
\r
1018 byte[] destination, int destOffset, int options ) {
\r
1020 // Lots of error checking and exception throwing
\r
1021 if( source == null ){
\r
1022 throw new NullPointerException( "Source array was null." );
\r
1024 if( destination == null ){
\r
1025 throw new NullPointerException( "Destination array was null." );
\r
1027 if( srcOffset < 0 || srcOffset + 3 >= source.length ){
\r
1028 throw new IllegalArgumentException( String.format(
\r
1029 "Source array with length %d cannot have offset of %d and still process four bytes.", source.length, srcOffset ) );
\r
1031 if( destOffset < 0 || destOffset +2 >= destination.length ){
\r
1032 throw new IllegalArgumentException( String.format(
\r
1033 "Destination array with length %d cannot have offset of %d and still store three bytes.", destination.length, destOffset ) );
\r
1037 byte[] DECODABET = getDecodabet( options );
\r
1040 if( source[ srcOffset + 2] == EQUALS_SIGN ) {
\r
1041 // Two ways to do the same thing. Don't know which way I like best.
\r
1042 //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
\r
1043 // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 );
\r
1044 int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
\r
1045 | ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 );
\r
1047 destination[ destOffset ] = (byte)( outBuff >>> 16 );
\r
1052 else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) {
\r
1053 // Two ways to do the same thing. Don't know which way I like best.
\r
1054 //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
\r
1055 // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
\r
1056 // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 );
\r
1057 int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
\r
1058 | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
\r
1059 | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 );
\r
1061 destination[ destOffset ] = (byte)( outBuff >>> 16 );
\r
1062 destination[ destOffset + 1 ] = (byte)( outBuff >>> 8 );
\r
1068 // Two ways to do the same thing. Don't know which way I like best.
\r
1069 //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
\r
1070 // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
\r
1071 // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 )
\r
1072 // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 );
\r
1073 int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
\r
1074 | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
\r
1075 | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6)
\r
1076 | ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) );
\r
1079 destination[ destOffset ] = (byte)( outBuff >> 16 );
\r
1080 destination[ destOffset + 1 ] = (byte)( outBuff >> 8 );
\r
1081 destination[ destOffset + 2 ] = (byte)( outBuff );
\r
1085 } // end decodeToBytes
\r
1092 * Low-level access to decoding ASCII characters in
\r
1093 * the form of a byte array. <strong>Ignores GUNZIP option, if
\r
1094 * it's set.</strong> This is not generally a recommended method,
\r
1095 * although it is used internally as part of the decoding process.
\r
1096 * Special case: if len = 0, an empty array is returned. Still,
\r
1097 * if you need more speed and reduced memory footprint (and aren't
\r
1098 * gzipping), consider this method.
\r
1100 * @param source The Base64 encoded data
\r
1101 * @return decoded data
\r
1104 public static byte[] decode( byte[] source ){
\r
1105 byte[] decoded = null;
\r
1107 decoded = decode( source, 0, source.length, Base64.NO_OPTIONS );
\r
1108 } catch( java.io.IOException ex ) {
\r
1109 assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage();
\r
1117 * Low-level access to decoding ASCII characters in
\r
1118 * the form of a byte array. <strong>Ignores GUNZIP option, if
\r
1119 * it's set.</strong> This is not generally a recommended method,
\r
1120 * although it is used internally as part of the decoding process.
\r
1121 * Special case: if len = 0, an empty array is returned. Still,
\r
1122 * if you need more speed and reduced memory footprint (and aren't
\r
1123 * gzipping), consider this method.
\r
1125 * @param source The Base64 encoded data
\r
1126 * @param off The offset of where to begin decoding
\r
1127 * @param len The length of characters to decode
\r
1128 * @param options Can specify options such as alphabet type to use
\r
1129 * @return decoded data
\r
1130 * @throws java.io.IOException If bogus characters exist in source data
\r
1133 public static byte[] decode( byte[] source, int off, int len, int options )
\r
1134 throws java.io.IOException {
\r
1136 // Lots of error checking and exception throwing
\r
1137 if( source == null ){
\r
1138 throw new NullPointerException( "Cannot decode null source array." );
\r
1140 if( off < 0 || off + len > source.length ){
\r
1141 throw new IllegalArgumentException( String.format(
\r
1142 "Source array with length %d cannot have offset of %d and process %d bytes.", source.length, off, len ) );
\r
1146 return new byte[0];
\r
1147 }else if( len < 4 ){
\r
1148 throw new IllegalArgumentException(
\r
1149 "Base64-encoded string must have at least four characters, but length specified was " + len );
\r
1152 byte[] DECODABET = getDecodabet( options );
\r
1154 int len34 = len * 3 / 4; // Estimate on array size
\r
1155 byte[] outBuff = new byte[ len34 ]; // Upper limit on size of output
\r
1156 int outBuffPosn = 0; // Keep track of where we're writing
\r
1158 byte[] b4 = new byte[4]; // Four byte buffer from source, eliminating white space
\r
1159 int b4Posn = 0; // Keep track of four byte input buffer
\r
1160 int i = 0; // Source array counter
\r
1161 byte sbiCrop = 0; // Low seven bits (ASCII) of input
\r
1162 byte sbiDecode = 0; // Special value from DECODABET
\r
1164 for( i = off; i < off+len; i++ ) { // Loop through source
\r
1166 sbiCrop = (byte)(source[i] & 0x7f); // Only the low seven bits
\r
1167 sbiDecode = DECODABET[ sbiCrop ]; // Special value
\r
1169 // White space, Equals sign, or legit Base64 character
\r
1170 // Note the values such as -5 and -9 in the
\r
1171 // DECODABETs at the top of the file.
\r
1172 if( sbiDecode >= WHITE_SPACE_ENC ) {
\r
1173 if( sbiDecode >= EQUALS_SIGN_ENC ) {
\r
1174 b4[ b4Posn++ ] = sbiCrop; // Save non-whitespace
\r
1175 if( b4Posn > 3 ) { // Time to decode?
\r
1176 outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn, options );
\r
1179 // If that was the equals sign, break out of 'for' loop
\r
1180 if( sbiCrop == EQUALS_SIGN ) {
\r
1182 } // end if: equals sign
\r
1183 } // end if: quartet built
\r
1184 } // end if: equals sign or better
\r
1185 } // end if: white space, equals sign or better
\r
1187 // There's a bad input character in the Base64 stream.
\r
1188 throw new java.io.IOException( String.format(
\r
1189 "Bad Base64 input character '%c' in array position %d", source[i], i ) );
\r
1191 } // each input character
\r
1193 byte[] out = new byte[ outBuffPosn ];
\r
1194 System.arraycopy( outBuff, 0, out, 0, outBuffPosn );
\r
1202 * Decodes data from Base64 notation, automatically
\r
1203 * detecting gzip-compressed data and decompressing it.
\r
1205 * @param s the string to decode
\r
1206 * @return the decoded data
\r
1207 * @throws java.io.IOException If there is a problem
\r
1210 public static byte[] decode( String s ) throws java.io.IOException {
\r
1211 return decode( s, NO_OPTIONS );
\r
1217 * Decodes data from Base64 notation, automatically
\r
1218 * detecting gzip-compressed data and decompressing it.
\r
1220 * @param s the string to decode
\r
1221 * @param options encode options such as URL_SAFE
\r
1222 * @return the decoded data
\r
1223 * @throws java.io.IOException if there is an error
\r
1224 * @throws NullPointerException if <tt>s</tt> is null
\r
1227 public static byte[] decode( String s, int options ) throws java.io.IOException {
\r
1230 throw new NullPointerException( "Input string was null." );
\r
1235 bytes = s.getBytes( PREFERRED_ENCODING );
\r
1237 catch( java.io.UnsupportedEncodingException uee ) {
\r
1238 bytes = s.getBytes();
\r
1243 bytes = decode( bytes, 0, bytes.length, options );
\r
1245 // Check to see if it's gzip-compressed
\r
1246 // GZIP Magic Two-Byte Number: 0x8b1f (35615)
\r
1247 boolean dontGunzip = (options & DONT_GUNZIP) != 0;
\r
1248 if( (bytes != null) && (bytes.length >= 4) && (!dontGunzip) ) {
\r
1250 int head = (bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00);
\r
1251 if( java.util.zip.GZIPInputStream.GZIP_MAGIC == head ) {
\r
1252 java.io.ByteArrayInputStream bais = null;
\r
1253 java.util.zip.GZIPInputStream gzis = null;
\r
1254 java.io.ByteArrayOutputStream baos = null;
\r
1255 byte[] buffer = new byte[2048];
\r
1259 baos = new java.io.ByteArrayOutputStream();
\r
1260 bais = new java.io.ByteArrayInputStream( bytes );
\r
1261 gzis = new java.util.zip.GZIPInputStream( bais );
\r
1263 while( ( length = gzis.read( buffer ) ) >= 0 ) {
\r
1264 baos.write(buffer,0,length);
\r
1265 } // end while: reading input
\r
1267 // No error? Get new bytes.
\r
1268 bytes = baos.toByteArray();
\r
1271 catch( java.io.IOException e ) {
\r
1272 e.printStackTrace();
\r
1273 // Just return originally-decoded bytes
\r
1276 try{ baos.close(); } catch( Exception e ){}
\r
1277 try{ gzis.close(); } catch( Exception e ){}
\r
1278 try{ bais.close(); } catch( Exception e ){}
\r
1281 } // end if: gzipped
\r
1282 } // end if: bytes.length >= 2
\r
1290 * Attempts to decode Base64 data and deserialize a Java
\r
1291 * Object within. Returns <tt>null</tt> if there was an error.
\r
1293 * @param encodedObject The Base64 data to decode
\r
1294 * @return The decoded and deserialized object
\r
1295 * @throws NullPointerException if encodedObject is null
\r
1296 * @throws java.io.IOException if there is a general error
\r
1297 * @throws ClassNotFoundException if the decoded object is of a
\r
1298 * class that cannot be found by the JVM
\r
1301 public static Object decodeToObject( String encodedObject )
\r
1302 throws java.io.IOException, java.lang.ClassNotFoundException {
\r
1303 return decodeToObject(encodedObject,NO_OPTIONS,null);
\r
1308 * Attempts to decode Base64 data and deserialize a Java
\r
1309 * Object within. Returns <tt>null</tt> if there was an error.
\r
1310 * If <tt>loader</tt> is not null, it will be the class loader
\r
1311 * used when deserializing.
\r
1313 * @param encodedObject The Base64 data to decode
\r
1314 * @param options Various parameters related to decoding
\r
1315 * @param loader Optional class loader to use in deserializing classes.
\r
1316 * @return The decoded and deserialized object
\r
1317 * @throws NullPointerException if encodedObject is null
\r
1318 * @throws java.io.IOException if there is a general error
\r
1319 * @throws ClassNotFoundException if the decoded object is of a
\r
1320 * class that cannot be found by the JVM
\r
1323 public static Object decodeToObject(
\r
1324 String encodedObject, int options, final ClassLoader loader )
\r
1325 throws java.io.IOException, java.lang.ClassNotFoundException {
\r
1327 // Decode and gunzip if necessary
\r
1328 byte[] objBytes = decode( encodedObject, options );
\r
1330 java.io.ByteArrayInputStream bais = null;
\r
1331 java.io.ObjectInputStream ois = null;
\r
1332 Object obj = null;
\r
1335 bais = new java.io.ByteArrayInputStream( objBytes );
\r
1337 // If no custom class loader is provided, use Java's builtin OIS.
\r
1338 if( loader == null ){
\r
1339 ois = new java.io.ObjectInputStream( bais );
\r
1340 } // end if: no loader provided
\r
1342 // Else make a customized object input stream that uses
\r
1343 // the provided class loader.
\r
1345 ois = new java.io.ObjectInputStream(bais){
\r
1346 @SuppressWarnings("unchecked")
\r
1348 public Class<?> resolveClass(java.io.ObjectStreamClass streamClass)
\r
1349 throws java.io.IOException, ClassNotFoundException {
\r
1350 Class c = Class.forName(streamClass.getName(), false, loader);
\r
1352 return super.resolveClass(streamClass);
\r
1354 return c; // Class loader knows of this class.
\r
1355 } // end else: not null
\r
1356 } // end resolveClass
\r
1358 } // end else: no custom class loader
\r
1360 obj = ois.readObject();
\r
1362 catch( java.io.IOException e ) {
\r
1363 throw e; // Catch and throw in order to execute finally{}
\r
1365 catch( java.lang.ClassNotFoundException e ) {
\r
1366 throw e; // Catch and throw in order to execute finally{}
\r
1369 try{ bais.close(); } catch( Exception e ){}
\r
1370 try{ ois.close(); } catch( Exception e ){}
\r
1374 } // end decodeObject
\r
1379 * Convenience method for encoding data to a file.
\r
1381 * <p>As of v 2.3, if there is a error,
\r
1382 * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
\r
1383 * In earlier versions, it just returned false, but
\r
1384 * in retrospect that's a pretty poor way to handle it.</p>
\r
1386 * @param dataToEncode byte array of data to encode in base64 form
\r
1387 * @param filename Filename for saving encoded data
\r
1388 * @throws java.io.IOException if there is an error
\r
1389 * @throws NullPointerException if dataToEncode is null
\r
1392 public static void encodeToFile( byte[] dataToEncode, String filename )
\r
1393 throws java.io.IOException {
\r
1395 if( dataToEncode == null ){
\r
1396 throw new NullPointerException( "Data to encode was null." );
\r
1399 Base64.OutputStream bos = null;
\r
1401 bos = new Base64.OutputStream(
\r
1402 new java.io.FileOutputStream( filename ), Base64.ENCODE );
\r
1403 bos.write( dataToEncode );
\r
1405 catch( java.io.IOException e ) {
\r
1406 throw e; // Catch and throw to execute finally{} block
\r
1407 } // end catch: java.io.IOException
\r
1409 try{ bos.close(); } catch( Exception e ){}
\r
1412 } // end encodeToFile
\r
1416 * Convenience method for decoding data to a file.
\r
1418 * <p>As of v 2.3, if there is a error,
\r
1419 * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
\r
1420 * In earlier versions, it just returned false, but
\r
1421 * in retrospect that's a pretty poor way to handle it.</p>
\r
1423 * @param dataToDecode Base64-encoded data as a string
\r
1424 * @param filename Filename for saving decoded data
\r
1425 * @throws java.io.IOException if there is an error
\r
1428 public static void decodeToFile( String dataToDecode, String filename )
\r
1429 throws java.io.IOException {
\r
1431 Base64.OutputStream bos = null;
\r
1433 bos = new Base64.OutputStream(
\r
1434 new java.io.FileOutputStream( filename ), Base64.DECODE );
\r
1435 bos.write( dataToDecode.getBytes( PREFERRED_ENCODING ) );
\r
1437 catch( java.io.IOException e ) {
\r
1438 throw e; // Catch and throw to execute finally{} block
\r
1439 } // end catch: java.io.IOException
\r
1441 try{ bos.close(); } catch( Exception e ){}
\r
1444 } // end decodeToFile
\r
1450 * Convenience method for reading a base64-encoded
\r
1451 * file and decoding it.
\r
1453 * <p>As of v 2.3, if there is a error,
\r
1454 * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
\r
1455 * In earlier versions, it just returned false, but
\r
1456 * in retrospect that's a pretty poor way to handle it.</p>
\r
1458 * @param filename Filename for reading encoded data
\r
1459 * @return decoded byte array
\r
1460 * @throws java.io.IOException if there is an error
\r
1463 public static byte[] decodeFromFile( String filename )
\r
1464 throws java.io.IOException {
\r
1466 byte[] decodedData = null;
\r
1467 Base64.InputStream bis = null;
\r
1470 // Set up some useful variables
\r
1471 java.io.File file = new java.io.File( filename );
\r
1472 byte[] buffer = null;
\r
1476 // Check for size of file
\r
1477 if( file.length() > Integer.MAX_VALUE )
\r
1479 throw new java.io.IOException( "File is too big for this convenience method (" + file.length() + " bytes)." );
\r
1480 } // end if: file too big for int index
\r
1481 buffer = new byte[ (int)file.length() ];
\r
1484 bis = new Base64.InputStream(
\r
1485 new java.io.BufferedInputStream(
\r
1486 new java.io.FileInputStream( file ) ), Base64.DECODE );
\r
1488 // Read until done
\r
1489 while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) {
\r
1490 length += numBytes;
\r
1493 // Save in a variable to return
\r
1494 decodedData = new byte[ length ];
\r
1495 System.arraycopy( buffer, 0, decodedData, 0, length );
\r
1498 catch( java.io.IOException e ) {
\r
1499 throw e; // Catch and release to execute finally{}
\r
1500 } // end catch: java.io.IOException
\r
1502 try{ bis.close(); } catch( Exception e) {}
\r
1505 return decodedData;
\r
1506 } // end decodeFromFile
\r
1511 * Convenience method for reading a binary file
\r
1512 * and base64-encoding it.
\r
1514 * <p>As of v 2.3, if there is a error,
\r
1515 * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
\r
1516 * In earlier versions, it just returned false, but
\r
1517 * in retrospect that's a pretty poor way to handle it.</p>
\r
1519 * @param filename Filename for reading binary data
\r
1520 * @return base64-encoded string
\r
1521 * @throws java.io.IOException if there is an error
\r
1524 public static String encodeFromFile( String filename )
\r
1525 throws java.io.IOException {
\r
1527 String encodedData = null;
\r
1528 Base64.InputStream bis = null;
\r
1531 // Set up some useful variables
\r
1532 java.io.File file = new java.io.File( filename );
\r
1533 byte[] buffer = new byte[ Math.max((int)(file.length() * 1.4),40) ]; // Need max() for math on small files (v2.2.1)
\r
1538 bis = new Base64.InputStream(
\r
1539 new java.io.BufferedInputStream(
\r
1540 new java.io.FileInputStream( file ) ), Base64.ENCODE );
\r
1542 // Read until done
\r
1543 while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) {
\r
1544 length += numBytes;
\r
1547 // Save in a variable to return
\r
1548 encodedData = new String( buffer, 0, length, Base64.PREFERRED_ENCODING );
\r
1551 catch( java.io.IOException e ) {
\r
1552 throw e; // Catch and release to execute finally{}
\r
1553 } // end catch: java.io.IOException
\r
1555 try{ bis.close(); } catch( Exception e) {}
\r
1558 return encodedData;
\r
1559 } // end encodeFromFile
\r
1562 * Reads <tt>infile</tt> and encodes it to <tt>outfile</tt>.
\r
1564 * @param infile Input file
\r
1565 * @param outfile Output file
\r
1566 * @throws java.io.IOException if there is an error
\r
1569 public static void encodeFileToFile( String infile, String outfile )
\r
1570 throws java.io.IOException {
\r
1572 String encoded = Base64.encodeFromFile( infile );
\r
1573 java.io.OutputStream out = null;
\r
1575 out = new java.io.BufferedOutputStream(
\r
1576 new java.io.FileOutputStream( outfile ) );
\r
1577 out.write( encoded.getBytes("US-ASCII") ); // Strict, 7-bit output.
\r
1579 catch( java.io.IOException e ) {
\r
1580 throw e; // Catch and release to execute finally{}
\r
1583 try { out.close(); }
\r
1584 catch( Exception ex ){}
\r
1586 } // end encodeFileToFile
\r
1590 * Reads <tt>infile</tt> and decodes it to <tt>outfile</tt>.
\r
1592 * @param infile Input file
\r
1593 * @param outfile Output file
\r
1594 * @throws java.io.IOException if there is an error
\r
1597 public static void decodeFileToFile( String infile, String outfile )
\r
1598 throws java.io.IOException {
\r
1600 byte[] decoded = Base64.decodeFromFile( infile );
\r
1601 java.io.OutputStream out = null;
\r
1603 out = new java.io.BufferedOutputStream(
\r
1604 new java.io.FileOutputStream( outfile ) );
\r
1605 out.write( decoded );
\r
1607 catch( java.io.IOException e ) {
\r
1608 throw e; // Catch and release to execute finally{}
\r
1611 try { out.close(); }
\r
1612 catch( Exception ex ){}
\r
1614 } // end decodeFileToFile
\r
1617 /* ******** I N N E R C L A S S I N P U T S T R E A M ******** */
\r
1622 * A {@link Base64.InputStream} will read data from another
\r
1623 * <tt>java.io.InputStream</tt>, given in the constructor,
\r
1624 * and encode/decode to/from Base64 notation on the fly.
\r
1629 public static class InputStream extends java.io.FilterInputStream {
\r
1631 private final boolean encode; // Encoding or decoding
\r
1632 private int position; // Current position in the buffer
\r
1633 private final byte[] buffer; // Small buffer holding converted data
\r
1634 private final int bufferLength; // Length of buffer (3 or 4)
\r
1635 private int numSigBytes; // Number of meaningful bytes in the buffer
\r
1636 private int lineLength;
\r
1637 private final boolean breakLines; // Break lines at less than 80 characters
\r
1638 private final int options; // Record options used to create the stream.
\r
1639 private final byte[] decodabet; // Local copies to avoid extra method calls
\r
1643 * Constructs a {@link Base64.InputStream} in DECODE mode.
\r
1645 * @param in the <tt>java.io.InputStream</tt> from which to read data.
\r
1648 public InputStream( java.io.InputStream in ) {
\r
1649 this( in, DECODE );
\r
1650 } // end constructor
\r
1654 * Constructs a {@link Base64.InputStream} in
\r
1655 * either ENCODE or DECODE mode.
\r
1657 * Valid options:<pre>
\r
1658 * ENCODE or DECODE: Encode or Decode as data is read.
\r
1659 * DO_BREAK_LINES: break lines at 76 characters
\r
1660 * (only meaningful when encoding)</i>
\r
1663 * Example: <code>new Base64.InputStream( in, Base64.DECODE )</code>
\r
1666 * @param in the <tt>java.io.InputStream</tt> from which to read data.
\r
1667 * @param options Specified options
\r
1668 * @see Base64#ENCODE
\r
1669 * @see Base64#DECODE
\r
1670 * @see Base64#DO_BREAK_LINES
\r
1673 public InputStream( java.io.InputStream in, int options ) {
\r
1676 this.options = options; // Record for later
\r
1677 this.breakLines = (options & DO_BREAK_LINES) > 0;
\r
1678 this.encode = (options & ENCODE) > 0;
\r
1679 this.bufferLength = encode ? 4 : 3;
\r
1680 this.buffer = new byte[ bufferLength ];
\r
1681 this.position = -1;
\r
1682 this.lineLength = 0;
\r
1683 this.decodabet = getDecodabet(options);
\r
1684 } // end constructor
\r
1687 * Reads enough of the input stream to convert
\r
1688 * to/from Base64 and returns the next byte.
\r
1690 * @return next byte
\r
1694 public int read() throws java.io.IOException {
\r
1696 // Do we need to get data?
\r
1697 if( position < 0 ) {
\r
1699 byte[] b3 = new byte[3];
\r
1700 int numBinaryBytes = 0;
\r
1701 for( int i = 0; i < 3; i++ ) {
\r
1702 int b = in.read();
\r
1704 // If end of stream, b is -1.
\r
1709 break; // out of for loop
\r
1710 } // end else: end of stream
\r
1712 } // end for: each needed input byte
\r
1714 if( numBinaryBytes > 0 ) {
\r
1715 encode3to4( b3, 0, numBinaryBytes, buffer, 0, options );
\r
1718 } // end if: got data
\r
1720 return -1; // Must be end of stream
\r
1722 } // end if: encoding
\r
1726 byte[] b4 = new byte[4];
\r
1728 for( i = 0; i < 4; i++ ) {
\r
1729 // Read four "meaningful" bytes:
\r
1731 do{ b = in.read(); }
\r
1732 while( b >= 0 && decodabet[ b & 0x7f ] <= WHITE_SPACE_ENC );
\r
1735 break; // Reads a -1 if end of stream
\r
1736 } // end if: end of stream
\r
1739 } // end for: each needed input byte
\r
1742 numSigBytes = decode4to3( b4, 0, buffer, 0, options );
\r
1744 } // end if: got four characters
\r
1745 else if( i == 0 ){
\r
1747 } // end else if: also padded correctly
\r
1749 // Must have broken out from above.
\r
1750 throw new java.io.IOException( "Improperly padded Base64 input." );
\r
1753 } // end else: decode
\r
1754 } // end else: get data
\r
1757 if( position >= 0 ) {
\r
1758 // End of relevant data?
\r
1759 if( /*!encode &&*/ position >= numSigBytes ){
\r
1761 } // end if: got data
\r
1763 if( encode && breakLines && lineLength >= MAX_LINE_LENGTH ) {
\r
1768 lineLength++; // This isn't important when decoding
\r
1769 // but throwing an extra "if" seems
\r
1770 // just as wasteful.
\r
1772 int b = buffer[ position++ ];
\r
1774 if( position >= bufferLength ) {
\r
1778 return b & 0xFF; // This is how you "cast" a byte that's
\r
1779 // intended to be unsigned.
\r
1781 } // end if: position >= 0
\r
1785 throw new java.io.IOException( "Error in Base64 code reading stream." );
\r
1791 * Calls {@link #read()} repeatedly until the end of stream
\r
1792 * is reached or <var>len</var> bytes are read.
\r
1793 * Returns number of bytes read into array or -1 if
\r
1794 * end of stream is encountered.
\r
1796 * @param dest array to hold values
\r
1797 * @param off offset for array
\r
1798 * @param len max number of bytes to read into array
\r
1799 * @return bytes read into array or -1 if end of stream is encountered.
\r
1803 public int read( byte[] dest, int off, int len )
\r
1804 throws java.io.IOException {
\r
1807 for( i = 0; i < len; i++ ) {
\r
1811 dest[off + i] = (byte) b;
\r
1813 else if( i == 0 ) {
\r
1817 break; // Out of 'for' loop
\r
1818 } // Out of 'for' loop
\r
1819 } // end for: each byte read
\r
1823 } // end inner class InputStream
\r
1830 /* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */
\r
1835 * A {@link Base64.OutputStream} will write data to another
\r
1836 * <tt>java.io.OutputStream</tt>, given in the constructor,
\r
1837 * and encode/decode to/from Base64 notation on the fly.
\r
1842 public static class OutputStream extends java.io.FilterOutputStream {
\r
1844 private final boolean encode;
\r
1845 private int position;
\r
1846 private byte[] buffer;
\r
1847 private final int bufferLength;
\r
1848 private int lineLength;
\r
1849 private final boolean breakLines;
\r
1850 private final byte[] b4; // Scratch used in a few places
\r
1851 private boolean suspendEncoding;
\r
1852 private final int options; // Record for later
\r
1853 private final byte[] decodabet; // Local copies to avoid extra method calls
\r
1856 * Constructs a {@link Base64.OutputStream} in ENCODE mode.
\r
1858 * @param out the <tt>java.io.OutputStream</tt> to which data will be written.
\r
1861 public OutputStream( java.io.OutputStream out ) {
\r
1862 this( out, ENCODE );
\r
1863 } // end constructor
\r
1867 * Constructs a {@link Base64.OutputStream} in
\r
1868 * either ENCODE or DECODE mode.
\r
1870 * Valid options:<pre>
\r
1871 * ENCODE or DECODE: Encode or Decode as data is read.
\r
1872 * DO_BREAK_LINES: don't break lines at 76 characters
\r
1873 * (only meaningful when encoding)</i>
\r
1876 * Example: <code>new Base64.OutputStream( out, Base64.ENCODE )</code>
\r
1878 * @param out the <tt>java.io.OutputStream</tt> to which data will be written.
\r
1879 * @param options Specified options.
\r
1880 * @see Base64#ENCODE
\r
1881 * @see Base64#DECODE
\r
1882 * @see Base64#DO_BREAK_LINES
\r
1885 public OutputStream( java.io.OutputStream out, int options ) {
\r
1887 this.breakLines = (options & DO_BREAK_LINES) != 0;
\r
1888 this.encode = (options & ENCODE) != 0;
\r
1889 this.bufferLength = encode ? 3 : 4;
\r
1890 this.buffer = new byte[ bufferLength ];
\r
1891 this.position = 0;
\r
1892 this.lineLength = 0;
\r
1893 this.suspendEncoding = false;
\r
1894 this.b4 = new byte[4];
\r
1895 this.options = options;
\r
1896 this.decodabet = getDecodabet(options);
\r
1897 } // end constructor
\r
1901 * Writes the byte to the output stream after
\r
1902 * converting to/from Base64 notation.
\r
1903 * When encoding, bytes are buffered three
\r
1904 * at a time before the output stream actually
\r
1905 * gets a write() call.
\r
1906 * When decoding, bytes are buffered four
\r
1909 * @param theByte the byte to write
\r
1913 public void write(int theByte)
\r
1914 throws java.io.IOException {
\r
1915 // Encoding suspended?
\r
1916 if( suspendEncoding ) {
\r
1917 this.out.write( theByte );
\r
1919 } // end if: supsended
\r
1923 buffer[ position++ ] = (byte)theByte;
\r
1924 if( position >= bufferLength ) { // Enough to encode.
\r
1926 this.out.write( encode3to4( b4, buffer, bufferLength, options ) );
\r
1929 if( breakLines && lineLength >= MAX_LINE_LENGTH ) {
\r
1930 this.out.write( NEW_LINE );
\r
1932 } // end if: end of line
\r
1935 } // end if: enough to output
\r
1936 } // end if: encoding
\r
1940 // Meaningful Base64 character?
\r
1941 if( decodabet[ theByte & 0x7f ] > WHITE_SPACE_ENC ) {
\r
1942 buffer[ position++ ] = (byte)theByte;
\r
1943 if( position >= bufferLength ) { // Enough to output.
\r
1945 int len = Base64.decode4to3( buffer, 0, b4, 0, options );
\r
1946 out.write( b4, 0, len );
\r
1948 } // end if: enough to output
\r
1949 } // end if: meaningful base64 character
\r
1950 else if( decodabet[ theByte & 0x7f ] != WHITE_SPACE_ENC ) {
\r
1951 throw new java.io.IOException( "Invalid character in Base64 data." );
\r
1952 } // end else: not white space either
\r
1953 } // end else: decoding
\r
1959 * Calls {@link #write(int)} repeatedly until <var>len</var>
\r
1960 * bytes are written.
\r
1962 * @param theBytes array from which to read bytes
\r
1963 * @param off offset for array
\r
1964 * @param len max number of bytes to read into array
\r
1968 public void write( byte[] theBytes, int off, int len )
\r
1969 throws java.io.IOException {
\r
1970 // Encoding suspended?
\r
1971 if( suspendEncoding ) {
\r
1972 this.out.write( theBytes, off, len );
\r
1974 } // end if: supsended
\r
1976 for( int i = 0; i < len; i++ ) {
\r
1977 write( theBytes[ off + i ] );
\r
1978 } // end for: each byte written
\r
1985 * Method added by PHIL. [Thanks, PHIL. -Rob]
\r
1986 * This pads the buffer without closing the stream.
\r
1987 * @throws java.io.IOException if there's an error.
\r
1989 public void flushBase64() throws java.io.IOException {
\r
1990 if( position > 0 ) {
\r
1992 out.write( encode3to4( b4, buffer, position, options ) );
\r
1994 } // end if: encoding
\r
1996 throw new java.io.IOException( "Base64 input not properly padded." );
\r
1997 } // end else: decoding
\r
1998 } // end if: buffer partially full
\r
2004 * Flushes and closes (I think, in the superclass) the stream.
\r
2009 public void close() throws java.io.IOException {
\r
2010 // 1. Ensure that pending characters are written
\r
2013 // 2. Actually close the stream
\r
2014 // Base class both flushes and closes.
\r
2024 * Suspends encoding of the stream.
\r
2025 * May be helpful if you need to embed a piece of
\r
2026 * base64-encoded data in a stream.
\r
2028 * @throws java.io.IOException if there's an error flushing
\r
2031 public void suspendEncoding() throws java.io.IOException {
\r
2033 this.suspendEncoding = true;
\r
2034 } // end suspendEncoding
\r
2038 * Resumes encoding of the stream.
\r
2039 * May be helpful if you need to embed a piece of
\r
2040 * base64-encoded data in a stream.
\r
2044 public void resumeEncoding() {
\r
2045 this.suspendEncoding = false;
\r
2046 } // end resumeEncoding
\r
2050 } // end inner class OutputStream
\r
2053 } // end class Base64
\r