]> nmode's Git Repositories - signal-cli/blob - src/main/java/cli/Base64.java
Add possibility to send messages via dbus daemon
[signal-cli] / src / main / java / cli / Base64.java
1 package cli;
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>Example:</p>
8 *
9 * <code>String encoded = Base64.encode( myByteArray );</code>
10 * <br />
11 * <code>byte[] myByteArray = Base64.decode( encoded );</code>
12 *
13 * <p>The <tt>options</tt> parameter, which appears in a few places, is used to pass
14 * several pieces of information to the encoder. In the "higher level" methods such as
15 * encodeBytes( bytes, options ) the options parameter can be used to indicate such
16 * things as first gzipping the bytes before encoding them, not inserting linefeeds,
17 * and encoding using the URL-safe and Ordered dialects.</p>
18 *
19 * <p>Note, according to <a href="http://www.faqs.org/rfcs/rfc3548.html">RFC3548</a>,
20 * Section 2.1, implementations should not add line feeds unless explicitly told
21 * to do so. I've got Base64 set to this behavior now, although earlier versions
22 * broke lines by default.</p>
23 *
24 * <p>The constants defined in Base64 can be OR-ed together to combine options, so you
25 * might make a call like this:</p>
26 *
27 * <code>String encoded = Base64.encodeBytes( mybytes, Base64.GZIP | Base64.DO_BREAK_LINES );</code>
28 * <p>to compress the data before encoding it and then making the output have newline characters.</p>
29 * <p>Also...</p>
30 * <code>String encoded = Base64.encodeBytes( crazyString.getBytes() );</code>
31 *
32 *
33 *
34 * <p>
35 * Change Log:
36 * </p>
37 * <ul>
38 * <li>v2.3.4 - Fixed bug when working with gzipped streams whereby flushing
39 * the Base64.OutputStream closed the Base64 encoding (by padding with equals
40 * signs) too soon. Also added an option to suppress the automatic decoding
41 * of gzipped streams. Also added experimental support for specifying a
42 * class loader when using the
43 * {@link #decodeToObject(java.lang.String, int, java.lang.ClassLoader)}
44 * method.</li>
45 * <li>v2.3.3 - Changed default char encoding to US-ASCII which reduces the internal Java
46 * footprint with its CharEncoders and so forth. Fixed some javadocs that were
47 * inconsistent. Removed imports and specified things like java.io.IOException
48 * explicitly inline.</li>
49 * <li>v2.3.2 - Reduced memory footprint! Finally refined the "guessing" of how big the
50 * final encoded data will be so that the code doesn't have to create two output
51 * arrays: an oversized initial one and then a final, exact-sized one. Big win
52 * when using the {@link #encodeBytesToBytes(byte[])} family of methods (and not
53 * using the gzip options which uses a different mechanism with streams and stuff).</li>
54 * <li>v2.3.1 - Added {@link #encodeBytesToBytes(byte[], int, int, int)} and some
55 * similar helper methods to be more efficient with memory by not returning a
56 * String but just a byte array.</li>
57 * <li>v2.3 - <strong>This is not a drop-in replacement!</strong> This is two years of comments
58 * and bug fixes queued up and finally executed. Thanks to everyone who sent
59 * me stuff, and I'm sorry I wasn't able to distribute your fixes to everyone else.
60 * Much bad coding was cleaned up including throwing exceptions where necessary
61 * instead of returning null values or something similar. Here are some changes
62 * that may affect you:
63 * <ul>
64 * <li><em>Does not break lines, by default.</em> This is to keep in compliance with
65 * <a href="http://www.faqs.org/rfcs/rfc3548.html">RFC3548</a>.</li>
66 * <li><em>Throws exceptions instead of returning null values.</em> Because some operations
67 * (especially those that may permit the GZIP option) use IO streams, there
68 * is a possiblity of an java.io.IOException being thrown. After some discussion and
69 * thought, I've changed the behavior of the methods to throw java.io.IOExceptions
70 * rather than return null if ever there's an error. I think this is more
71 * appropriate, though it will require some changes to your code. Sorry,
72 * it should have been done this way to begin with.</li>
73 * <li><em>Removed all references to System.out, System.err, and the like.</em>
74 * Shame on me. All I can say is sorry they were ever there.</li>
75 * <li><em>Throws NullPointerExceptions and IllegalArgumentExceptions</em> as needed
76 * such as when passed arrays are null or offsets are invalid.</li>
77 * <li>Cleaned up as much javadoc as I could to avoid any javadoc warnings.
78 * This was especially annoying before for people who were thorough in their
79 * own projects and then had gobs of javadoc warnings on this file.</li>
80 * </ul>
81 * <li>v2.2.1 - Fixed bug using URL_SAFE and ORDERED encodings. Fixed bug
82 * when using very small files (~< 40 bytes).</li>
83 * <li>v2.2 - Added some helper methods for encoding/decoding directly from
84 * one file to the next. Also added a main() method to support command line
85 * encoding/decoding from one file to the next. Also added these Base64 dialects:
86 * <ol>
87 * <li>The default is RFC3548 format.</li>
88 * <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.URLSAFE_FORMAT) generates
89 * URL and file name friendly format as described in Section 4 of RFC3548.
90 * http://www.faqs.org/rfcs/rfc3548.html</li>
91 * <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.ORDERED_FORMAT) generates
92 * URL and file name friendly format that preserves lexical ordering as described
93 * in http://www.faqs.org/qa/rfcc-1940.html</li>
94 * </ol>
95 * Special thanks to Jim Kellerman at <a href="http://www.powerset.com/">http://www.powerset.com/</a>
96 * for contributing the new Base64 dialects.
97 * </li>
98 *
99 * <li>v2.1 - Cleaned up javadoc comments and unused variables and methods. Added
100 * some convenience methods for reading and writing to and from files.</li>
101 * <li>v2.0.2 - Now specifies UTF-8 encoding in places where the code fails on systems
102 * with other encodings (like EBCDIC).</li>
103 * <li>v2.0.1 - Fixed an error when decoding a single byte, that is, when the
104 * encoded data was a single byte.</li>
105 * <li>v2.0 - I got rid of methods that used booleans to set options.
106 * Now everything is more consolidated and cleaner. The code now detects
107 * when data that's being decoded is gzip-compressed and will decompress it
108 * automatically. Generally things are cleaner. You'll probably have to
109 * change some method calls that you were making to support the new
110 * options format (<tt>int</tt>s that you "OR" together).</li>
111 * <li>v1.5.1 - Fixed bug when decompressing and decoding to a
112 * byte[] using <tt>decode( String s, boolean gzipCompressed )</tt>.
113 * Added the ability to "suspend" encoding in the Output Stream so
114 * you can turn on and off the encoding if you need to embed base64
115 * data in an otherwise "normal" stream (like an XML file).</li>
116 * <li>v1.5 - Output stream pases on flush() command but doesn't do anything itself.
117 * This helps when using GZIP streams.
118 * Added the ability to GZip-compress objects before encoding them.</li>
119 * <li>v1.4 - Added helper methods to read/write files.</li>
120 * <li>v1.3.6 - Fixed OutputStream.flush() so that 'position' is reset.</li>
121 * <li>v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in input stream
122 * where last buffer being read, if not completely full, was not returned.</li>
123 * <li>v1.3.4 - Fixed when "improperly padded stream" error was thrown at the wrong time.</li>
124 * <li>v1.3.3 - Fixed I/O streams which were totally messed up.</li>
125 * </ul>
126 *
127 * <p>
128 * I am placing this code in the Public Domain. Do with it as you will.
129 * This software comes with no guarantees or warranties but with
130 * plenty of well-wishing instead!
131 * Please visit <a href="http://iharder.net/base64">http://iharder.net/base64</a>
132 * periodically to check for updates or to contribute improvements.
133 * </p>
134 *
135 * @author Robert Harder
136 * @author rob@iharder.net
137 * @version 2.3.3
138 */
139 public class Base64 {
140
141 /* ******** P U B L I C F I E L D S ******** */
142
143
144 /**
145 * No options specified. Value is zero.
146 */
147 public final static int NO_OPTIONS = 0;
148
149 /**
150 * Specify encoding in first bit. Value is one.
151 */
152 public final static int ENCODE = 1;
153
154
155 /**
156 * Specify decoding in first bit. Value is zero.
157 */
158 public final static int DECODE = 0;
159
160
161 /**
162 * Specify that data should be gzip-compressed in second bit. Value is two.
163 */
164 public final static int GZIP = 2;
165
166 /**
167 * Specify that gzipped data should <em>not</em> be automatically gunzipped.
168 */
169 public final static int DONT_GUNZIP = 4;
170
171
172 /**
173 * Do break lines when encoding. Value is 8.
174 */
175 public final static int DO_BREAK_LINES = 8;
176
177 /**
178 * Encode using Base64-like encoding that is URL- and Filename-safe as described
179 * in Section 4 of RFC3548:
180 * <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>.
181 * It is important to note that data encoded this way is <em>not</em> officially valid Base64,
182 * or at the very least should not be called Base64 without also specifying that is
183 * was encoded using the URL- and Filename-safe dialect.
184 */
185 public final static int URL_SAFE = 16;
186
187
188 /**
189 * Encode using the special "ordered" dialect of Base64 described here:
190 * <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>.
191 */
192 public final static int ORDERED = 32;
193
194
195 /* ******** P R I V A T E F I E L D S ******** */
196
197
198 /**
199 * Maximum line length (76) of Base64 output.
200 */
201 private final static int MAX_LINE_LENGTH = 76;
202
203
204 /**
205 * The equals sign (=) as a byte.
206 */
207 private final static byte EQUALS_SIGN = (byte) '=';
208
209
210 /**
211 * The new line character (\n) as a byte.
212 */
213 private final static byte NEW_LINE = (byte) '\n';
214
215
216 /**
217 * Preferred encoding.
218 */
219 private final static String PREFERRED_ENCODING = "US-ASCII";
220
221
222 private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding
223 private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding
224
225
226 /* ******** S T A N D A R D B A S E 6 4 A L P H A B E T ******** */
227
228 /**
229 * The 64 valid Base64 values.
230 */
231 /* Host platform me be something funny like EBCDIC, so we hardcode these values. */
232 private final static byte[] _STANDARD_ALPHABET = {
233 (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G',
234 (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N',
235 (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U',
236 (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z',
237 (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g',
238 (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n',
239 (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u',
240 (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z',
241 (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5',
242 (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '+', (byte) '/'
243 };
244
245
246 /**
247 * Translates a Base64 value to either its 6-bit reconstruction value
248 * or a negative number indicating some other meaning.
249 */
250 private final static byte[] _STANDARD_DECODABET = {
251 -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8
252 -5, -5, // Whitespace: Tab and Linefeed
253 -9, -9, // Decimal 11 - 12
254 -5, // Whitespace: Carriage Return
255 -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26
256 -9, -9, -9, -9, -9, // Decimal 27 - 31
257 -5, // Whitespace: Space
258 -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42
259 62, // Plus sign at decimal 43
260 -9, -9, -9, // Decimal 44 - 46
261 63, // Slash at decimal 47
262 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine
263 -9, -9, -9, // Decimal 58 - 60
264 -1, // Equals sign at decimal 61
265 -9, -9, -9, // Decimal 62 - 64
266 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N'
267 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z'
268 -9, -9, -9, -9, -9, -9, // Decimal 91 - 96
269 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm'
270 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z'
271 -9, -9, -9, -9 // Decimal 123 - 126
272 /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139
273 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
274 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
275 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
276 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
277 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
278 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
279 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
280 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
281 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */
282 };
283
284
285 /* ******** U R L S A F E B A S E 6 4 A L P H A B E T ******** */
286
287 /**
288 * Used in the URL- and Filename-safe dialect described in Section 4 of RFC3548:
289 * <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>.
290 * Notice that the last two bytes become "hyphen" and "underscore" instead of "plus" and "slash."
291 */
292 private final static byte[] _URL_SAFE_ALPHABET = {
293 (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G',
294 (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N',
295 (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U',
296 (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z',
297 (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g',
298 (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n',
299 (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u',
300 (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z',
301 (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5',
302 (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '-', (byte) '_'
303 };
304
305 /**
306 * Used in decoding URL- and Filename-safe dialects of Base64.
307 */
308 private final static byte[] _URL_SAFE_DECODABET = {
309 -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8
310 -5, -5, // Whitespace: Tab and Linefeed
311 -9, -9, // Decimal 11 - 12
312 -5, // Whitespace: Carriage Return
313 -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26
314 -9, -9, -9, -9, -9, // Decimal 27 - 31
315 -5, // Whitespace: Space
316 -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42
317 -9, // Plus sign at decimal 43
318 -9, // Decimal 44
319 62, // Minus sign at decimal 45
320 -9, // Decimal 46
321 -9, // Slash at decimal 47
322 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine
323 -9, -9, -9, // Decimal 58 - 60
324 -1, // Equals sign at decimal 61
325 -9, -9, -9, // Decimal 62 - 64
326 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N'
327 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z'
328 -9, -9, -9, -9, // Decimal 91 - 94
329 63, // Underscore at decimal 95
330 -9, // Decimal 96
331 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm'
332 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z'
333 -9, -9, -9, -9 // Decimal 123 - 126
334 /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139
335 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
336 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
337 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
338 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
339 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
340 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
341 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
342 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
343 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */
344 };
345
346
347
348 /* ******** O R D E R E D B A S E 6 4 A L P H A B E T ******** */
349
350 /**
351 * I don't get the point of this technique, but someone requested it,
352 * and it is described here:
353 * <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>.
354 */
355 private final static byte[] _ORDERED_ALPHABET = {
356 (byte) '-',
357 (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4',
358 (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9',
359 (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G',
360 (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N',
361 (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U',
362 (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z',
363 (byte) '_',
364 (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g',
365 (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n',
366 (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u',
367 (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z'
368 };
369
370 /**
371 * Used in decoding the "ordered" dialect of Base64.
372 */
373 private final static byte[] _ORDERED_DECODABET = {
374 -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8
375 -5, -5, // Whitespace: Tab and Linefeed
376 -9, -9, // Decimal 11 - 12
377 -5, // Whitespace: Carriage Return
378 -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26
379 -9, -9, -9, -9, -9, // Decimal 27 - 31
380 -5, // Whitespace: Space
381 -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42
382 -9, // Plus sign at decimal 43
383 -9, // Decimal 44
384 0, // Minus sign at decimal 45
385 -9, // Decimal 46
386 -9, // Slash at decimal 47
387 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, // Numbers zero through nine
388 -9, -9, -9, // Decimal 58 - 60
389 -1, // Equals sign at decimal 61
390 -9, -9, -9, // Decimal 62 - 64
391 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, // Letters 'A' through 'M'
392 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, // Letters 'N' through 'Z'
393 -9, -9, -9, -9, // Decimal 91 - 94
394 37, // Underscore at decimal 95
395 -9, // Decimal 96
396 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, // Letters 'a' through 'm'
397 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, // Letters 'n' through 'z'
398 -9, -9, -9, -9 // Decimal 123 - 126
399 /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139
400 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
401 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
402 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
403 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
404 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
405 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
406 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
407 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
408 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */
409 };
410
411
412 /* ******** D E T E R M I N E W H I C H A L H A B E T ******** */
413
414
415 /**
416 * Returns one of the _SOMETHING_ALPHABET byte arrays depending on
417 * the options specified.
418 * It's possible, though silly, to specify ORDERED <b>and</b> URLSAFE
419 * in which case one of them will be picked, though there is
420 * no guarantee as to which one will be picked.
421 */
422 private final static byte[] getAlphabet(int options) {
423 if ((options & URL_SAFE) == URL_SAFE) {
424 return _URL_SAFE_ALPHABET;
425 } else if ((options & ORDERED) == ORDERED) {
426 return _ORDERED_ALPHABET;
427 } else {
428 return _STANDARD_ALPHABET;
429 }
430 } // end getAlphabet
431
432
433 /**
434 * Returns one of the _SOMETHING_DECODABET byte arrays depending on
435 * the options specified.
436 * It's possible, though silly, to specify ORDERED and URL_SAFE
437 * in which case one of them will be picked, though there is
438 * no guarantee as to which one will be picked.
439 */
440 private final static byte[] getDecodabet(int options) {
441 if ((options & URL_SAFE) == URL_SAFE) {
442 return _URL_SAFE_DECODABET;
443 } else if ((options & ORDERED) == ORDERED) {
444 return _ORDERED_DECODABET;
445 } else {
446 return _STANDARD_DECODABET;
447 }
448 } // end getAlphabet
449
450
451 /**
452 * Defeats instantiation.
453 */
454 private Base64() {
455 }
456
457
458 public static int getEncodedLengthWithoutPadding(int unencodedLength) {
459 int remainderBytes = unencodedLength % 3;
460 int paddingBytes = 0;
461
462 if (remainderBytes != 0)
463 paddingBytes = 3 - remainderBytes;
464
465 return (((int) ((unencodedLength + 2) / 3)) * 4) - paddingBytes;
466 }
467
468 public static int getEncodedBytesForTarget(int targetSize) {
469 return ((int) (targetSize * 3)) / 4;
470 }
471
472
473 /* ******** E N C O D I N G M E T H O D S ******** */
474
475
476 /**
477 * Encodes up to the first three bytes of array <var>threeBytes</var>
478 * and returns a four-byte array in Base64 notation.
479 * The actual number of significant bytes in your array is
480 * given by <var>numSigBytes</var>.
481 * The array <var>threeBytes</var> needs only be as big as
482 * <var>numSigBytes</var>.
483 * Code can reuse a byte array by passing a four-byte array as <var>b4</var>.
484 *
485 * @param b4 A reusable byte array to reduce array instantiation
486 * @param threeBytes the array to convert
487 * @param numSigBytes the number of significant bytes in your array
488 * @return four byte array in Base64 notation.
489 * @since 1.5.1
490 */
491 private static byte[] encode3to4(byte[] b4, byte[] threeBytes, int numSigBytes, int options) {
492 encode3to4(threeBytes, 0, numSigBytes, b4, 0, options);
493 return b4;
494 } // end encode3to4
495
496
497 /**
498 * <p>Encodes up to three bytes of the array <var>source</var>
499 * and writes the resulting four Base64 bytes to <var>destination</var>.
500 * The source and destination arrays can be manipulated
501 * anywhere along their length by specifying
502 * <var>srcOffset</var> and <var>destOffset</var>.
503 * This method does not check to make sure your arrays
504 * are large enough to accomodate <var>srcOffset</var> + 3 for
505 * the <var>source</var> array or <var>destOffset</var> + 4 for
506 * the <var>destination</var> array.
507 * The actual number of significant bytes in your array is
508 * given by <var>numSigBytes</var>.</p>
509 * <p>This is the lowest level of the encoding methods with
510 * all possible parameters.</p>
511 *
512 * @param source the array to convert
513 * @param srcOffset the index where conversion begins
514 * @param numSigBytes the number of significant bytes in your array
515 * @param destination the array to hold the conversion
516 * @param destOffset the index where output will be put
517 * @return the <var>destination</var> array
518 * @since 1.3
519 */
520 private static byte[] encode3to4(
521 byte[] source, int srcOffset, int numSigBytes,
522 byte[] destination, int destOffset, int options) {
523
524 byte[] ALPHABET = getAlphabet(options);
525
526 // 1 2 3
527 // 01234567890123456789012345678901 Bit position
528 // --------000000001111111122222222 Array position from threeBytes
529 // --------| || || || | Six bit groups to index ALPHABET
530 // >>18 >>12 >> 6 >> 0 Right shift necessary
531 // 0x3f 0x3f 0x3f Additional AND
532
533 // Create buffer with zero-padding if there are only one or two
534 // significant bytes passed in the array.
535 // We have to shift left 24 in order to flush out the 1's that appear
536 // when Java treats a value as negative that is cast from a byte to an int.
537 int inBuff = (numSigBytes > 0 ? ((source[srcOffset] << 24) >>> 8) : 0)
538 | (numSigBytes > 1 ? ((source[srcOffset + 1] << 24) >>> 16) : 0)
539 | (numSigBytes > 2 ? ((source[srcOffset + 2] << 24) >>> 24) : 0);
540
541 switch (numSigBytes) {
542 case 3:
543 destination[destOffset] = ALPHABET[(inBuff >>> 18)];
544 destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f];
545 destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f];
546 destination[destOffset + 3] = ALPHABET[(inBuff) & 0x3f];
547 return destination;
548
549 case 2:
550 destination[destOffset] = ALPHABET[(inBuff >>> 18)];
551 destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f];
552 destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f];
553 destination[destOffset + 3] = EQUALS_SIGN;
554 return destination;
555
556 case 1:
557 destination[destOffset] = ALPHABET[(inBuff >>> 18)];
558 destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f];
559 destination[destOffset + 2] = EQUALS_SIGN;
560 destination[destOffset + 3] = EQUALS_SIGN;
561 return destination;
562
563 default:
564 return destination;
565 } // end switch
566 } // end encode3to4
567
568
569 /**
570 * Performs Base64 encoding on the <code>raw</code> ByteBuffer,
571 * writing it to the <code>encoded</code> ByteBuffer.
572 * This is an experimental feature. Currently it does not
573 * pass along any options (such as {@link #DO_BREAK_LINES}
574 * or {@link #GZIP}.
575 *
576 * @param raw input buffer
577 * @param encoded output buffer
578 * @since 2.3
579 */
580 public static void encode(java.nio.ByteBuffer raw, java.nio.ByteBuffer encoded) {
581 byte[] raw3 = new byte[3];
582 byte[] enc4 = new byte[4];
583
584 while (raw.hasRemaining()) {
585 int rem = Math.min(3, raw.remaining());
586 raw.get(raw3, 0, rem);
587 Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS);
588 encoded.put(enc4);
589 } // end input remaining
590 }
591
592
593 /**
594 * Performs Base64 encoding on the <code>raw</code> ByteBuffer,
595 * writing it to the <code>encoded</code> CharBuffer.
596 * This is an experimental feature. Currently it does not
597 * pass along any options (such as {@link #DO_BREAK_LINES}
598 * or {@link #GZIP}.
599 *
600 * @param raw input buffer
601 * @param encoded output buffer
602 * @since 2.3
603 */
604 public static void encode(java.nio.ByteBuffer raw, java.nio.CharBuffer encoded) {
605 byte[] raw3 = new byte[3];
606 byte[] enc4 = new byte[4];
607
608 while (raw.hasRemaining()) {
609 int rem = Math.min(3, raw.remaining());
610 raw.get(raw3, 0, rem);
611 Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS);
612 for (int i = 0; i < 4; i++) {
613 encoded.put((char) (enc4[i] & 0xFF));
614 }
615 } // end input remaining
616 }
617
618
619 /**
620 * Serializes an object and returns the Base64-encoded
621 * version of that serialized object.
622 *
623 * <p>As of v 2.3, if the object
624 * cannot be serialized or there is another error,
625 * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
626 * In earlier versions, it just returned a null value, but
627 * in retrospect that's a pretty poor way to handle it.</p>
628 *
629 * The object is not GZip-compressed before being encoded.
630 *
631 * @param serializableObject The object to encode
632 * @return The Base64-encoded object
633 * @throws java.io.IOException if there is an error
634 * @throws NullPointerException if serializedObject is null
635 * @since 1.4
636 */
637 public static String encodeObject(java.io.Serializable serializableObject)
638 throws java.io.IOException {
639 return encodeObject(serializableObject, NO_OPTIONS);
640 } // end encodeObject
641
642
643 /**
644 * Serializes an object and returns the Base64-encoded
645 * version of that serialized object.
646 *
647 * <p>As of v 2.3, if the object
648 * cannot be serialized or there is another error,
649 * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
650 * In earlier versions, it just returned a null value, but
651 * in retrospect that's a pretty poor way to handle it.</p>
652 *
653 * The object is not GZip-compressed before being encoded.
654 *
655 * Example options:<pre>
656 * GZIP: gzip-compresses object before encoding it.
657 * DO_BREAK_LINES: break lines at 76 characters
658 * </pre>
659 *
660 * Example: <code>encodeObject( myObj, Base64.GZIP )</code> or
661 *
662 * Example: <code>encodeObject( myObj, Base64.GZIP | Base64.DO_BREAK_LINES )</code>
663 *
664 * @param serializableObject The object to encode
665 * @param options Specified options
666 * @return The Base64-encoded object
667 * @throws java.io.IOException if there is an error
668 * @see Base64#GZIP
669 * @see Base64#DO_BREAK_LINES
670 * @since 2.0
671 */
672 public static String encodeObject(java.io.Serializable serializableObject, int options)
673 throws java.io.IOException {
674
675 if (serializableObject == null) {
676 throw new NullPointerException("Cannot serialize a null object.");
677 } // end if: null
678
679 // Streams
680 java.io.ByteArrayOutputStream baos = null;
681 java.io.OutputStream b64os = null;
682 java.util.zip.GZIPOutputStream gzos = null;
683 java.io.ObjectOutputStream oos = null;
684
685
686 try {
687 // ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream
688 baos = new java.io.ByteArrayOutputStream();
689 b64os = new Base64.OutputStream(baos, ENCODE | options);
690 if ((options & GZIP) != 0) {
691 // Gzip
692 gzos = new java.util.zip.GZIPOutputStream(b64os);
693 oos = new java.io.ObjectOutputStream(gzos);
694 } else {
695 // Not gzipped
696 oos = new java.io.ObjectOutputStream(b64os);
697 }
698 oos.writeObject(serializableObject);
699 } // end try
700 catch (java.io.IOException e) {
701 // Catch it and then throw it immediately so that
702 // the finally{} block is called for cleanup.
703 throw e;
704 } // end catch
705 finally {
706 try {
707 oos.close();
708 } catch (Exception e) {
709 }
710 try {
711 gzos.close();
712 } catch (Exception e) {
713 }
714 try {
715 b64os.close();
716 } catch (Exception e) {
717 }
718 try {
719 baos.close();
720 } catch (Exception e) {
721 }
722 } // end finally
723
724 // Return value according to relevant encoding.
725 try {
726 return new String(baos.toByteArray(), PREFERRED_ENCODING);
727 } // end try
728 catch (java.io.UnsupportedEncodingException uue) {
729 // Fall back to some Java default
730 return new String(baos.toByteArray());
731 } // end catch
732
733 } // end encode
734
735
736 /**
737 * Encodes a byte array into Base64 notation.
738 * Does not GZip-compress data.
739 *
740 * @param source The data to convert
741 * @return The data in Base64-encoded form
742 * @throws NullPointerException if source array is null
743 * @since 1.4
744 */
745 public static String encodeBytes(byte[] source) {
746 // Since we're not going to have the GZIP encoding turned on,
747 // we're not going to have an java.io.IOException thrown, so
748 // we should not force the user to have to catch it.
749 String encoded = null;
750 try {
751 encoded = encodeBytes(source, 0, source.length, NO_OPTIONS);
752 } catch (java.io.IOException ex) {
753 assert false : ex.getMessage();
754 } // end catch
755 assert encoded != null;
756 return encoded;
757 } // end encodeBytes
758
759
760 public static String encodeBytesWithoutPadding(byte[] source, int offset, int length) {
761 String encoded = null;
762
763 try {
764 encoded = encodeBytes(source, offset, length, NO_OPTIONS);
765 } catch (java.io.IOException ex) {
766 assert false : ex.getMessage();
767 }
768
769 assert encoded != null;
770
771 if (encoded.charAt(encoded.length() - 2) == '=')
772 return encoded.substring(0, encoded.length() - 2);
773 else if (encoded.charAt(encoded.length() - 1) == '=')
774 return encoded.substring(0, encoded.length() - 1);
775 else return encoded;
776
777 }
778
779 public static String encodeBytesWithoutPadding(byte[] source) {
780 return encodeBytesWithoutPadding(source, 0, source.length);
781 }
782
783
784 /**
785 * Encodes a byte array into Base64 notation.
786 * <p>
787 * Example options:<pre>
788 * GZIP: gzip-compresses object before encoding it.
789 * DO_BREAK_LINES: break lines at 76 characters
790 * <i>Note: Technically, this makes your encoding non-compliant.</i>
791 * </pre>
792 * <p>
793 * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
794 * <p>
795 * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES )</code>
796 *
797 *
798 * <p>As of v 2.3, if there is an error with the GZIP stream,
799 * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
800 * In earlier versions, it just returned a null value, but
801 * in retrospect that's a pretty poor way to handle it.</p>
802 *
803 * @param source The data to convert
804 * @param options Specified options
805 * @return The Base64-encoded data as a String
806 * @throws java.io.IOException if there is an error
807 * @throws NullPointerException if source array is null
808 * @see Base64#GZIP
809 * @see Base64#DO_BREAK_LINES
810 * @since 2.0
811 */
812 public static String encodeBytes(byte[] source, int options) throws java.io.IOException {
813 return encodeBytes(source, 0, source.length, options);
814 } // end encodeBytes
815
816
817 /**
818 * Encodes a byte array into Base64 notation.
819 * Does not GZip-compress data.
820 *
821 * <p>As of v 2.3, if there is an error,
822 * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
823 * In earlier versions, it just returned a null value, but
824 * in retrospect that's a pretty poor way to handle it.</p>
825 *
826 * @param source The data to convert
827 * @param off Offset in array where conversion should begin
828 * @param len Length of data to convert
829 * @return The Base64-encoded data as a String
830 * @throws NullPointerException if source array is null
831 * @throws IllegalArgumentException if source array, offset, or length are invalid
832 * @since 1.4
833 */
834 public static String encodeBytes(byte[] source, int off, int len) {
835 // Since we're not going to have the GZIP encoding turned on,
836 // we're not going to have an java.io.IOException thrown, so
837 // we should not force the user to have to catch it.
838 String encoded = null;
839 try {
840 encoded = encodeBytes(source, off, len, NO_OPTIONS);
841 } catch (java.io.IOException ex) {
842 assert false : ex.getMessage();
843 } // end catch
844 assert encoded != null;
845 return encoded;
846 } // end encodeBytes
847
848
849 /**
850 * Encodes a byte array into Base64 notation.
851 * <p>
852 * Example options:<pre>
853 * GZIP: gzip-compresses object before encoding it.
854 * DO_BREAK_LINES: break lines at 76 characters
855 * <i>Note: Technically, this makes your encoding non-compliant.</i>
856 * </pre>
857 * <p>
858 * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
859 * <p>
860 * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES )</code>
861 *
862 *
863 * <p>As of v 2.3, if there is an error with the GZIP stream,
864 * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
865 * In earlier versions, it just returned a null value, but
866 * in retrospect that's a pretty poor way to handle it.</p>
867 *
868 * @param source The data to convert
869 * @param off Offset in array where conversion should begin
870 * @param len Length of data to convert
871 * @param options Specified options
872 * @return The Base64-encoded data as a String
873 * @throws java.io.IOException if there is an error
874 * @throws NullPointerException if source array is null
875 * @throws IllegalArgumentException if source array, offset, or length are invalid
876 * @see Base64#GZIP
877 * @see Base64#DO_BREAK_LINES
878 * @since 2.0
879 */
880 public static String encodeBytes(byte[] source, int off, int len, int options) throws java.io.IOException {
881 byte[] encoded = encodeBytesToBytes(source, off, len, options);
882
883 // Return value according to relevant encoding.
884 try {
885 return new String(encoded, PREFERRED_ENCODING);
886 } // end try
887 catch (java.io.UnsupportedEncodingException uue) {
888 return new String(encoded);
889 } // end catch
890
891 } // end encodeBytes
892
893
894 /**
895 * Similar to {@link #encodeBytes(byte[])} but returns
896 * a byte array instead of instantiating a String. This is more efficient
897 * if you're working with I/O streams and have large data sets to encode.
898 *
899 * @param source The data to convert
900 * @return The Base64-encoded data as a byte[] (of ASCII characters)
901 * @throws NullPointerException if source array is null
902 * @since 2.3.1
903 */
904 public static byte[] encodeBytesToBytes(byte[] source) {
905 byte[] encoded = null;
906 try {
907 encoded = encodeBytesToBytes(source, 0, source.length, Base64.NO_OPTIONS);
908 } catch (java.io.IOException ex) {
909 assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage();
910 }
911 return encoded;
912 }
913
914
915 /**
916 * Similar to {@link #encodeBytes(byte[], int, int, int)} but returns
917 * a byte array instead of instantiating a String. This is more efficient
918 * if you're working with I/O streams and have large data sets to encode.
919 *
920 * @param source The data to convert
921 * @param off Offset in array where conversion should begin
922 * @param len Length of data to convert
923 * @param options Specified options
924 * @return The Base64-encoded data as a String
925 * @throws java.io.IOException if there is an error
926 * @throws NullPointerException if source array is null
927 * @throws IllegalArgumentException if source array, offset, or length are invalid
928 * @see Base64#GZIP
929 * @see Base64#DO_BREAK_LINES
930 * @since 2.3.1
931 */
932 public static byte[] encodeBytesToBytes(byte[] source, int off, int len, int options) throws java.io.IOException {
933
934 if (source == null) {
935 throw new NullPointerException("Cannot serialize a null array.");
936 } // end if: null
937
938 if (off < 0) {
939 throw new IllegalArgumentException("Cannot have negative offset: " + off);
940 } // end if: off < 0
941
942 if (len < 0) {
943 throw new IllegalArgumentException("Cannot have length offset: " + len);
944 } // end if: len < 0
945
946 if (off + len > source.length) {
947 throw new IllegalArgumentException(
948 String.format("Cannot have offset of %d and length of %d with array of length %d", off, len, source.length));
949 } // end if: off < 0
950
951
952 // Compress?
953 if ((options & GZIP) != 0) {
954 java.io.ByteArrayOutputStream baos = null;
955 java.util.zip.GZIPOutputStream gzos = null;
956 Base64.OutputStream b64os = null;
957
958 try {
959 // GZip -> Base64 -> ByteArray
960 baos = new java.io.ByteArrayOutputStream();
961 b64os = new Base64.OutputStream(baos, ENCODE | options);
962 gzos = new java.util.zip.GZIPOutputStream(b64os);
963
964 gzos.write(source, off, len);
965 gzos.close();
966 } // end try
967 catch (java.io.IOException e) {
968 // Catch it and then throw it immediately so that
969 // the finally{} block is called for cleanup.
970 throw e;
971 } // end catch
972 finally {
973 try {
974 gzos.close();
975 } catch (Exception e) {
976 }
977 try {
978 b64os.close();
979 } catch (Exception e) {
980 }
981 try {
982 baos.close();
983 } catch (Exception e) {
984 }
985 } // end finally
986
987 return baos.toByteArray();
988 } // end if: compress
989
990 // Else, don't compress. Better not to use streams at all then.
991 else {
992 boolean breakLines = (options & DO_BREAK_LINES) > 0;
993
994 //int len43 = len * 4 / 3;
995 //byte[] outBuff = new byte[ ( len43 ) // Main 4:3
996 // + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding
997 // + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines
998 // Try to determine more precisely how big the array needs to be.
999 // If we get it right, we don't have to do an array copy, and
1000 // we save a bunch of memory.
1001 int encLen = (len / 3) * 4 + (len % 3 > 0 ? 4 : 0); // Bytes needed for actual encoding
1002 if (breakLines) {
1003 encLen += encLen / MAX_LINE_LENGTH; // Plus extra newline characters
1004 }
1005 byte[] outBuff = new byte[encLen];
1006
1007
1008 int d = 0;
1009 int e = 0;
1010 int len2 = len - 2;
1011 int lineLength = 0;
1012 for (; d < len2; d += 3, e += 4) {
1013 encode3to4(source, d + off, 3, outBuff, e, options);
1014
1015 lineLength += 4;
1016 if (breakLines && lineLength >= MAX_LINE_LENGTH) {
1017 outBuff[e + 4] = NEW_LINE;
1018 e++;
1019 lineLength = 0;
1020 } // end if: end of line
1021 } // en dfor: each piece of array
1022
1023 if (d < len) {
1024 encode3to4(source, d + off, len - d, outBuff, e, options);
1025 e += 4;
1026 } // end if: some padding needed
1027
1028
1029 // Only resize array if we didn't guess it right.
1030 if (e < outBuff.length - 1) {
1031 byte[] finalOut = new byte[e];
1032 System.arraycopy(outBuff, 0, finalOut, 0, e);
1033 //System.err.println("Having to resize array from " + outBuff.length + " to " + e );
1034 return finalOut;
1035 } else {
1036 //System.err.println("No need to resize array.");
1037 return outBuff;
1038 }
1039
1040 } // end else: don't compress
1041
1042 } // end encodeBytesToBytes
1043
1044
1045
1046
1047
1048 /* ******** D E C O D I N G M E T H O D S ******** */
1049
1050
1051 /**
1052 * Decodes four bytes from array <var>source</var>
1053 * and writes the resulting bytes (up to three of them)
1054 * to <var>destination</var>.
1055 * The source and destination arrays can be manipulated
1056 * anywhere along their length by specifying
1057 * <var>srcOffset</var> and <var>destOffset</var>.
1058 * This method does not check to make sure your arrays
1059 * are large enough to accomodate <var>srcOffset</var> + 4 for
1060 * the <var>source</var> array or <var>destOffset</var> + 3 for
1061 * the <var>destination</var> array.
1062 * This method returns the actual number of bytes that
1063 * were converted from the Base64 encoding.
1064 * <p>This is the lowest level of the decoding methods with
1065 * all possible parameters.</p>
1066 *
1067 * @param source the array to convert
1068 * @param srcOffset the index where conversion begins
1069 * @param destination the array to hold the conversion
1070 * @param destOffset the index where output will be put
1071 * @param options alphabet type is pulled from this (standard, url-safe, ordered)
1072 * @return the number of decoded bytes converted
1073 * @throws NullPointerException if source or destination arrays are null
1074 * @throws IllegalArgumentException if srcOffset or destOffset are invalid
1075 * or there is not enough room in the array.
1076 * @since 1.3
1077 */
1078 private static int decode4to3(
1079 byte[] source, int srcOffset,
1080 byte[] destination, int destOffset, int options) {
1081
1082 // Lots of error checking and exception throwing
1083 if (source == null) {
1084 throw new NullPointerException("Source array was null.");
1085 } // end if
1086 if (destination == null) {
1087 throw new NullPointerException("Destination array was null.");
1088 } // end if
1089 if (srcOffset < 0 || srcOffset + 3 >= source.length) {
1090 throw new IllegalArgumentException(String.format(
1091 "Source array with length %d cannot have offset of %d and still process four bytes.", source.length, srcOffset));
1092 } // end if
1093 if (destOffset < 0 || destOffset + 2 >= destination.length) {
1094 throw new IllegalArgumentException(String.format(
1095 "Destination array with length %d cannot have offset of %d and still store three bytes.", destination.length, destOffset));
1096 } // end if
1097
1098
1099 byte[] DECODABET = getDecodabet(options);
1100
1101 // Example: Dk==
1102 if (source[srcOffset + 2] == EQUALS_SIGN) {
1103 // Two ways to do the same thing. Don't know which way I like best.
1104 //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
1105 // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 );
1106 int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18)
1107 | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12);
1108
1109 destination[destOffset] = (byte) (outBuff >>> 16);
1110 return 1;
1111 }
1112
1113 // Example: DkL=
1114 else if (source[srcOffset + 3] == EQUALS_SIGN) {
1115 // Two ways to do the same thing. Don't know which way I like best.
1116 //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
1117 // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
1118 // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 );
1119 int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18)
1120 | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12)
1121 | ((DECODABET[source[srcOffset + 2]] & 0xFF) << 6);
1122
1123 destination[destOffset] = (byte) (outBuff >>> 16);
1124 destination[destOffset + 1] = (byte) (outBuff >>> 8);
1125 return 2;
1126 }
1127
1128 // Example: DkLE
1129 else {
1130 // Two ways to do the same thing. Don't know which way I like best.
1131 //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
1132 // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
1133 // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 )
1134 // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 );
1135 int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18)
1136 | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12)
1137 | ((DECODABET[source[srcOffset + 2]] & 0xFF) << 6)
1138 | ((DECODABET[source[srcOffset + 3]] & 0xFF));
1139
1140
1141 destination[destOffset] = (byte) (outBuff >> 16);
1142 destination[destOffset + 1] = (byte) (outBuff >> 8);
1143 destination[destOffset + 2] = (byte) (outBuff);
1144
1145 return 3;
1146 }
1147 } // end decodeToBytes
1148
1149
1150 /**
1151 * Low-level access to decoding ASCII characters in
1152 * the form of a byte array. <strong>Ignores GUNZIP option, if
1153 * it's set.</strong> This is not generally a recommended method,
1154 * although it is used internally as part of the decoding process.
1155 * Special case: if len = 0, an empty array is returned. Still,
1156 * if you need more speed and reduced memory footprint (and aren't
1157 * gzipping), consider this method.
1158 *
1159 * @param source The Base64 encoded data
1160 * @return decoded data
1161 * @since 2.3.1
1162 */
1163 public static byte[] decode(byte[] source) {
1164 byte[] decoded = null;
1165 try {
1166 decoded = decode(source, 0, source.length, Base64.NO_OPTIONS);
1167 } catch (java.io.IOException ex) {
1168 assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage();
1169 }
1170 return decoded;
1171 }
1172
1173
1174 /**
1175 * Low-level access to decoding ASCII characters in
1176 * the form of a byte array. <strong>Ignores GUNZIP option, if
1177 * it's set.</strong> This is not generally a recommended method,
1178 * although it is used internally as part of the decoding process.
1179 * Special case: if len = 0, an empty array is returned. Still,
1180 * if you need more speed and reduced memory footprint (and aren't
1181 * gzipping), consider this method.
1182 *
1183 * @param source The Base64 encoded data
1184 * @param off The offset of where to begin decoding
1185 * @param len The length of characters to decode
1186 * @param options Can specify options such as alphabet type to use
1187 * @return decoded data
1188 * @throws java.io.IOException If bogus characters exist in source data
1189 * @since 1.3
1190 */
1191 public static byte[] decode(byte[] source, int off, int len, int options)
1192 throws java.io.IOException {
1193
1194 // Lots of error checking and exception throwing
1195 if (source == null) {
1196 throw new NullPointerException("Cannot decode null source array.");
1197 } // end if
1198 if (off < 0 || off + len > source.length) {
1199 throw new IllegalArgumentException(String.format(
1200 "Source array with length %d cannot have offset of %d and process %d bytes.", source.length, off, len));
1201 } // end if
1202
1203 if (len == 0) {
1204 return new byte[0];
1205 } else if (len < 4) {
1206 throw new IllegalArgumentException(
1207 "Base64-encoded string must have at least four characters, but length specified was " + len);
1208 } // end if
1209
1210 byte[] DECODABET = getDecodabet(options);
1211
1212 int len34 = len * 3 / 4; // Estimate on array size
1213 byte[] outBuff = new byte[len34]; // Upper limit on size of output
1214 int outBuffPosn = 0; // Keep track of where we're writing
1215
1216 byte[] b4 = new byte[4]; // Four byte buffer from source, eliminating white space
1217 int b4Posn = 0; // Keep track of four byte input buffer
1218 int i = 0; // Source array counter
1219 byte sbiCrop = 0; // Low seven bits (ASCII) of input
1220 byte sbiDecode = 0; // Special value from DECODABET
1221
1222 for (i = off; i < off + len; i++) { // Loop through source
1223
1224 sbiCrop = (byte) (source[i] & 0x7f); // Only the low seven bits
1225 sbiDecode = DECODABET[sbiCrop]; // Special value
1226
1227 // White space, Equals sign, or legit Base64 character
1228 // Note the values such as -5 and -9 in the
1229 // DECODABETs at the top of the file.
1230 if (sbiDecode >= WHITE_SPACE_ENC) {
1231 if (sbiDecode >= EQUALS_SIGN_ENC) {
1232 b4[b4Posn++] = sbiCrop; // Save non-whitespace
1233 if (b4Posn > 3) { // Time to decode?
1234 outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn, options);
1235 b4Posn = 0;
1236
1237 // If that was the equals sign, break out of 'for' loop
1238 if (sbiCrop == EQUALS_SIGN) {
1239 break;
1240 } // end if: equals sign
1241 } // end if: quartet built
1242 } // end if: equals sign or better
1243 } // end if: white space, equals sign or better
1244 else {
1245 // There's a bad input character in the Base64 stream.
1246 throw new java.io.IOException(String.format(
1247 "Bad Base64 input character '%c' in array position %d", source[i], i));
1248 } // end else:
1249 } // each input character
1250
1251 byte[] out = new byte[outBuffPosn];
1252 System.arraycopy(outBuff, 0, out, 0, outBuffPosn);
1253 return out;
1254 } // end decode
1255
1256
1257 /**
1258 * Decodes data from Base64 notation, automatically
1259 * detecting gzip-compressed data and decompressing it.
1260 *
1261 * @param s the string to decode
1262 * @return the decoded data
1263 * @throws java.io.IOException If there is a problem
1264 * @since 1.4
1265 */
1266 public static byte[] decode(String s) throws java.io.IOException {
1267 return decode(s, NO_OPTIONS);
1268 }
1269
1270
1271 public static byte[] decodeWithoutPadding(String source) throws java.io.IOException {
1272 int padding = source.length() % 4;
1273
1274 if (padding == 1) source = source + "=";
1275 else if (padding == 2) source = source + "==";
1276 else if (padding == 3) source = source + "=";
1277
1278 return decode(source);
1279 }
1280
1281
1282 /**
1283 * Decodes data from Base64 notation, automatically
1284 * detecting gzip-compressed data and decompressing it.
1285 *
1286 * @param s the string to decode
1287 * @param options encode options such as URL_SAFE
1288 * @return the decoded data
1289 * @throws java.io.IOException if there is an error
1290 * @throws NullPointerException if <tt>s</tt> is null
1291 * @since 1.4
1292 */
1293 public static byte[] decode(String s, int options) throws java.io.IOException {
1294
1295 if (s == null) {
1296 throw new NullPointerException("Input string was null.");
1297 } // end if
1298
1299 byte[] bytes;
1300 try {
1301 bytes = s.getBytes(PREFERRED_ENCODING);
1302 } // end try
1303 catch (java.io.UnsupportedEncodingException uee) {
1304 bytes = s.getBytes();
1305 } // end catch
1306 //</change>
1307
1308 // Decode
1309 bytes = decode(bytes, 0, bytes.length, options);
1310
1311 // Check to see if it's gzip-compressed
1312 // GZIP Magic Two-Byte Number: 0x8b1f (35615)
1313 boolean dontGunzip = (options & DONT_GUNZIP) != 0;
1314 if ((bytes != null) && (bytes.length >= 4) && (!dontGunzip)) {
1315
1316 int head = ((int) bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00);
1317 if (java.util.zip.GZIPInputStream.GZIP_MAGIC == head) {
1318 java.io.ByteArrayInputStream bais = null;
1319 java.util.zip.GZIPInputStream gzis = null;
1320 java.io.ByteArrayOutputStream baos = null;
1321 byte[] buffer = new byte[2048];
1322 int length = 0;
1323
1324 try {
1325 baos = new java.io.ByteArrayOutputStream();
1326 bais = new java.io.ByteArrayInputStream(bytes);
1327 gzis = new java.util.zip.GZIPInputStream(bais);
1328
1329 while ((length = gzis.read(buffer)) >= 0) {
1330 baos.write(buffer, 0, length);
1331 } // end while: reading input
1332
1333 // No error? Get new bytes.
1334 bytes = baos.toByteArray();
1335
1336 } // end try
1337 catch (java.io.IOException e) {
1338 e.printStackTrace();
1339 // Just return originally-decoded bytes
1340 } // end catch
1341 finally {
1342 try {
1343 baos.close();
1344 } catch (Exception e) {
1345 }
1346 try {
1347 gzis.close();
1348 } catch (Exception e) {
1349 }
1350 try {
1351 bais.close();
1352 } catch (Exception e) {
1353 }
1354 } // end finally
1355
1356 } // end if: gzipped
1357 } // end if: bytes.length >= 2
1358
1359 return bytes;
1360 } // end decode
1361
1362
1363 /**
1364 * Attempts to decode Base64 data and deserialize a Java
1365 * Object within. Returns <tt>null</tt> if there was an error.
1366 *
1367 * @param encodedObject The Base64 data to decode
1368 * @return The decoded and deserialized object
1369 * @throws NullPointerException if encodedObject is null
1370 * @throws java.io.IOException if there is a general error
1371 * @throws ClassNotFoundException if the decoded object is of a
1372 * class that cannot be found by the JVM
1373 * @since 1.5
1374 */
1375 public static Object decodeToObject(String encodedObject)
1376 throws java.io.IOException, java.lang.ClassNotFoundException {
1377 return decodeToObject(encodedObject, NO_OPTIONS, null);
1378 }
1379
1380
1381 /**
1382 * Attempts to decode Base64 data and deserialize a Java
1383 * Object within. Returns <tt>null</tt> if there was an error.
1384 * If <tt>loader</tt> is not null, it will be the class loader
1385 * used when deserializing.
1386 *
1387 * @param encodedObject The Base64 data to decode
1388 * @param options Various parameters related to decoding
1389 * @param loader Optional class loader to use in deserializing classes.
1390 * @return The decoded and deserialized object
1391 * @throws NullPointerException if encodedObject is null
1392 * @throws java.io.IOException if there is a general error
1393 * @throws ClassNotFoundException if the decoded object is of a
1394 * class that cannot be found by the JVM
1395 * @since 2.3.4
1396 */
1397 public static Object decodeToObject(
1398 String encodedObject, int options, final ClassLoader loader)
1399 throws java.io.IOException, java.lang.ClassNotFoundException {
1400
1401 // Decode and gunzip if necessary
1402 byte[] objBytes = decode(encodedObject, options);
1403
1404 java.io.ByteArrayInputStream bais = null;
1405 java.io.ObjectInputStream ois = null;
1406 Object obj = null;
1407
1408 try {
1409 bais = new java.io.ByteArrayInputStream(objBytes);
1410
1411 // If no custom class loader is provided, use Java's builtin OIS.
1412 if (loader == null) {
1413 ois = new java.io.ObjectInputStream(bais);
1414 } // end if: no loader provided
1415
1416 // Else make a customized object input stream that uses
1417 // the provided class loader.
1418 else {
1419 ois = new java.io.ObjectInputStream(bais) {
1420 @Override
1421 public Class<?> resolveClass(java.io.ObjectStreamClass streamClass)
1422 throws java.io.IOException, ClassNotFoundException {
1423 Class c = Class.forName(streamClass.getName(), false, loader);
1424 if (c == null) {
1425 return super.resolveClass(streamClass);
1426 } else {
1427 return c; // Class loader knows of this class.
1428 } // end else: not null
1429 } // end resolveClass
1430 }; // end ois
1431 } // end else: no custom class loader
1432
1433 obj = ois.readObject();
1434 } // end try
1435 catch (java.io.IOException e) {
1436 throw e; // Catch and throw in order to execute finally{}
1437 } // end catch
1438 catch (java.lang.ClassNotFoundException e) {
1439 throw e; // Catch and throw in order to execute finally{}
1440 } // end catch
1441 finally {
1442 try {
1443 bais.close();
1444 } catch (Exception e) {
1445 }
1446 try {
1447 ois.close();
1448 } catch (Exception e) {
1449 }
1450 } // end finally
1451
1452 return obj;
1453 } // end decodeObject
1454
1455
1456 /**
1457 * Convenience method for encoding data to a file.
1458 *
1459 * <p>As of v 2.3, if there is a error,
1460 * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
1461 * In earlier versions, it just returned false, but
1462 * in retrospect that's a pretty poor way to handle it.</p>
1463 *
1464 * @param dataToEncode byte array of data to encode in base64 form
1465 * @param filename Filename for saving encoded data
1466 * @throws java.io.IOException if there is an error
1467 * @throws NullPointerException if dataToEncode is null
1468 * @since 2.1
1469 */
1470 public static void encodeToFile(byte[] dataToEncode, String filename)
1471 throws java.io.IOException {
1472
1473 if (dataToEncode == null) {
1474 throw new NullPointerException("Data to encode was null.");
1475 } // end iff
1476
1477 Base64.OutputStream bos = null;
1478 try {
1479 bos = new Base64.OutputStream(
1480 new java.io.FileOutputStream(filename), Base64.ENCODE);
1481 bos.write(dataToEncode);
1482 } // end try
1483 catch (java.io.IOException e) {
1484 throw e; // Catch and throw to execute finally{} block
1485 } // end catch: java.io.IOException
1486 finally {
1487 try {
1488 bos.close();
1489 } catch (Exception e) {
1490 }
1491 } // end finally
1492
1493 } // end encodeToFile
1494
1495
1496 /**
1497 * Convenience method for decoding data to a file.
1498 *
1499 * <p>As of v 2.3, if there is a error,
1500 * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
1501 * In earlier versions, it just returned false, but
1502 * in retrospect that's a pretty poor way to handle it.</p>
1503 *
1504 * @param dataToDecode Base64-encoded data as a string
1505 * @param filename Filename for saving decoded data
1506 * @throws java.io.IOException if there is an error
1507 * @since 2.1
1508 */
1509 public static void decodeToFile(String dataToDecode, String filename)
1510 throws java.io.IOException {
1511
1512 Base64.OutputStream bos = null;
1513 try {
1514 bos = new Base64.OutputStream(
1515 new java.io.FileOutputStream(filename), Base64.DECODE);
1516 bos.write(dataToDecode.getBytes(PREFERRED_ENCODING));
1517 } // end try
1518 catch (java.io.IOException e) {
1519 throw e; // Catch and throw to execute finally{} block
1520 } // end catch: java.io.IOException
1521 finally {
1522 try {
1523 bos.close();
1524 } catch (Exception e) {
1525 }
1526 } // end finally
1527
1528 } // end decodeToFile
1529
1530
1531 /**
1532 * Convenience method for reading a base64-encoded
1533 * file and decoding it.
1534 *
1535 * <p>As of v 2.3, if there is a error,
1536 * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
1537 * In earlier versions, it just returned false, but
1538 * in retrospect that's a pretty poor way to handle it.</p>
1539 *
1540 * @param filename Filename for reading encoded data
1541 * @return decoded byte array
1542 * @throws java.io.IOException if there is an error
1543 * @since 2.1
1544 */
1545 public static byte[] decodeFromFile(String filename)
1546 throws java.io.IOException {
1547
1548 byte[] decodedData = null;
1549 Base64.InputStream bis = null;
1550 try {
1551 // Set up some useful variables
1552 java.io.File file = new java.io.File(filename);
1553 byte[] buffer = null;
1554 int length = 0;
1555 int numBytes = 0;
1556
1557 // Check for size of file
1558 if (file.length() > Integer.MAX_VALUE) {
1559 throw new java.io.IOException("File is too big for this convenience method (" + file.length() + " bytes).");
1560 } // end if: file too big for int index
1561 buffer = new byte[(int) file.length()];
1562
1563 // Open a stream
1564 bis = new Base64.InputStream(
1565 new java.io.BufferedInputStream(
1566 new java.io.FileInputStream(file)), Base64.DECODE);
1567
1568 // Read until done
1569 while ((numBytes = bis.read(buffer, length, 4096)) >= 0) {
1570 length += numBytes;
1571 } // end while
1572
1573 // Save in a variable to return
1574 decodedData = new byte[length];
1575 System.arraycopy(buffer, 0, decodedData, 0, length);
1576
1577 } // end try
1578 catch (java.io.IOException e) {
1579 throw e; // Catch and release to execute finally{}
1580 } // end catch: java.io.IOException
1581 finally {
1582 try {
1583 bis.close();
1584 } catch (Exception e) {
1585 }
1586 } // end finally
1587
1588 return decodedData;
1589 } // end decodeFromFile
1590
1591
1592 /**
1593 * Convenience method for reading a binary file
1594 * and base64-encoding it.
1595 *
1596 * <p>As of v 2.3, if there is a error,
1597 * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
1598 * In earlier versions, it just returned false, but
1599 * in retrospect that's a pretty poor way to handle it.</p>
1600 *
1601 * @param filename Filename for reading binary data
1602 * @return base64-encoded string
1603 * @throws java.io.IOException if there is an error
1604 * @since 2.1
1605 */
1606 public static String encodeFromFile(String filename)
1607 throws java.io.IOException {
1608
1609 String encodedData = null;
1610 Base64.InputStream bis = null;
1611 try {
1612 // Set up some useful variables
1613 java.io.File file = new java.io.File(filename);
1614 byte[] buffer = new byte[Math.max((int) (file.length() * 1.4), 40)]; // Need max() for math on small files (v2.2.1)
1615 int length = 0;
1616 int numBytes = 0;
1617
1618 // Open a stream
1619 bis = new Base64.InputStream(
1620 new java.io.BufferedInputStream(
1621 new java.io.FileInputStream(file)), Base64.ENCODE);
1622
1623 // Read until done
1624 while ((numBytes = bis.read(buffer, length, 4096)) >= 0) {
1625 length += numBytes;
1626 } // end while
1627
1628 // Save in a variable to return
1629 encodedData = new String(buffer, 0, length, Base64.PREFERRED_ENCODING);
1630
1631 } // end try
1632 catch (java.io.IOException e) {
1633 throw e; // Catch and release to execute finally{}
1634 } // end catch: java.io.IOException
1635 finally {
1636 try {
1637 bis.close();
1638 } catch (Exception e) {
1639 }
1640 } // end finally
1641
1642 return encodedData;
1643 } // end encodeFromFile
1644
1645 /**
1646 * Reads <tt>infile</tt> and encodes it to <tt>outfile</tt>.
1647 *
1648 * @param infile Input file
1649 * @param outfile Output file
1650 * @throws java.io.IOException if there is an error
1651 * @since 2.2
1652 */
1653 public static void encodeFileToFile(String infile, String outfile)
1654 throws java.io.IOException {
1655
1656 String encoded = Base64.encodeFromFile(infile);
1657 java.io.OutputStream out = null;
1658 try {
1659 out = new java.io.BufferedOutputStream(
1660 new java.io.FileOutputStream(outfile));
1661 out.write(encoded.getBytes("US-ASCII")); // Strict, 7-bit output.
1662 } // end try
1663 catch (java.io.IOException e) {
1664 throw e; // Catch and release to execute finally{}
1665 } // end catch
1666 finally {
1667 try {
1668 out.close();
1669 } catch (Exception ex) {
1670 }
1671 } // end finally
1672 } // end encodeFileToFile
1673
1674
1675 /**
1676 * Reads <tt>infile</tt> and decodes it to <tt>outfile</tt>.
1677 *
1678 * @param infile Input file
1679 * @param outfile Output file
1680 * @throws java.io.IOException if there is an error
1681 * @since 2.2
1682 */
1683 public static void decodeFileToFile(String infile, String outfile)
1684 throws java.io.IOException {
1685
1686 byte[] decoded = Base64.decodeFromFile(infile);
1687 java.io.OutputStream out = null;
1688 try {
1689 out = new java.io.BufferedOutputStream(
1690 new java.io.FileOutputStream(outfile));
1691 out.write(decoded);
1692 } // end try
1693 catch (java.io.IOException e) {
1694 throw e; // Catch and release to execute finally{}
1695 } // end catch
1696 finally {
1697 try {
1698 out.close();
1699 } catch (Exception ex) {
1700 }
1701 } // end finally
1702 } // end decodeFileToFile
1703
1704
1705 /* ******** I N N E R C L A S S I N P U T S T R E A M ******** */
1706
1707
1708 /**
1709 * A {@link Base64.InputStream} will read data from another
1710 * <tt>java.io.InputStream</tt>, given in the constructor,
1711 * and encode/decode to/from Base64 notation on the fly.
1712 *
1713 * @see Base64
1714 * @since 1.3
1715 */
1716 public static class InputStream extends java.io.FilterInputStream {
1717
1718 private boolean encode; // Encoding or decoding
1719 private int position; // Current position in the buffer
1720 private byte[] buffer; // Small buffer holding converted data
1721 private int bufferLength; // Length of buffer (3 or 4)
1722 private int numSigBytes; // Number of meaningful bytes in the buffer
1723 private int lineLength;
1724 private boolean breakLines; // Break lines at less than 80 characters
1725 private int options; // Record options used to create the stream.
1726 private byte[] decodabet; // Local copies to avoid extra method calls
1727
1728
1729 /**
1730 * Constructs a {@link Base64.InputStream} in DECODE mode.
1731 *
1732 * @param in the <tt>java.io.InputStream</tt> from which to read data.
1733 * @since 1.3
1734 */
1735 public InputStream(java.io.InputStream in) {
1736 this(in, DECODE);
1737 } // end constructor
1738
1739
1740 /**
1741 * Constructs a {@link Base64.InputStream} in
1742 * either ENCODE or DECODE mode.
1743 *
1744 * Valid options:<pre>
1745 * ENCODE or DECODE: Encode or Decode as data is read.
1746 * DO_BREAK_LINES: break lines at 76 characters
1747 * (only meaningful when encoding)</i>
1748 * </pre>
1749 *
1750 * Example: <code>new Base64.InputStream( in, Base64.DECODE )</code>
1751 *
1752 * @param in the <tt>java.io.InputStream</tt> from which to read data.
1753 * @param options Specified options
1754 * @see Base64#ENCODE
1755 * @see Base64#DECODE
1756 * @see Base64#DO_BREAK_LINES
1757 * @since 2.0
1758 */
1759 public InputStream(java.io.InputStream in, int options) {
1760
1761 super(in);
1762 this.options = options; // Record for later
1763 this.breakLines = (options & DO_BREAK_LINES) > 0;
1764 this.encode = (options & ENCODE) > 0;
1765 this.bufferLength = encode ? 4 : 3;
1766 this.buffer = new byte[bufferLength];
1767 this.position = -1;
1768 this.lineLength = 0;
1769 this.decodabet = getDecodabet(options);
1770 } // end constructor
1771
1772 /**
1773 * Reads enough of the input stream to convert
1774 * to/from Base64 and returns the next byte.
1775 *
1776 * @return next byte
1777 * @since 1.3
1778 */
1779 @Override
1780 public int read() throws java.io.IOException {
1781
1782 // Do we need to get data?
1783 if (position < 0) {
1784 if (encode) {
1785 byte[] b3 = new byte[3];
1786 int numBinaryBytes = 0;
1787 for (int i = 0; i < 3; i++) {
1788 int b = in.read();
1789
1790 // If end of stream, b is -1.
1791 if (b >= 0) {
1792 b3[i] = (byte) b;
1793 numBinaryBytes++;
1794 } else {
1795 break; // out of for loop
1796 } // end else: end of stream
1797
1798 } // end for: each needed input byte
1799
1800 if (numBinaryBytes > 0) {
1801 encode3to4(b3, 0, numBinaryBytes, buffer, 0, options);
1802 position = 0;
1803 numSigBytes = 4;
1804 } // end if: got data
1805 else {
1806 return -1; // Must be end of stream
1807 } // end else
1808 } // end if: encoding
1809
1810 // Else decoding
1811 else {
1812 byte[] b4 = new byte[4];
1813 int i = 0;
1814 for (i = 0; i < 4; i++) {
1815 // Read four "meaningful" bytes:
1816 int b = 0;
1817 do {
1818 b = in.read();
1819 }
1820 while (b >= 0 && decodabet[b & 0x7f] <= WHITE_SPACE_ENC);
1821
1822 if (b < 0) {
1823 break; // Reads a -1 if end of stream
1824 } // end if: end of stream
1825
1826 b4[i] = (byte) b;
1827 } // end for: each needed input byte
1828
1829 if (i == 4) {
1830 numSigBytes = decode4to3(b4, 0, buffer, 0, options);
1831 position = 0;
1832 } // end if: got four characters
1833 else if (i == 0) {
1834 return -1;
1835 } // end else if: also padded correctly
1836 else {
1837 // Must have broken out from above.
1838 throw new java.io.IOException("Improperly padded Base64 input.");
1839 } // end
1840
1841 } // end else: decode
1842 } // end else: get data
1843
1844 // Got data?
1845 if (position >= 0) {
1846 // End of relevant data?
1847 if ( /*!encode &&*/ position >= numSigBytes) {
1848 return -1;
1849 } // end if: got data
1850
1851 if (encode && breakLines && lineLength >= MAX_LINE_LENGTH) {
1852 lineLength = 0;
1853 return '\n';
1854 } // end if
1855 else {
1856 lineLength++; // This isn't important when decoding
1857 // but throwing an extra "if" seems
1858 // just as wasteful.
1859
1860 int b = buffer[position++];
1861
1862 if (position >= bufferLength) {
1863 position = -1;
1864 } // end if: end
1865
1866 return b & 0xFF; // This is how you "cast" a byte that's
1867 // intended to be unsigned.
1868 } // end else
1869 } // end if: position >= 0
1870
1871 // Else error
1872 else {
1873 throw new java.io.IOException("Error in Base64 code reading stream.");
1874 } // end else
1875 } // end read
1876
1877
1878 /**
1879 * Calls {@link #read()} repeatedly until the end of stream
1880 * is reached or <var>len</var> bytes are read.
1881 * Returns number of bytes read into array or -1 if
1882 * end of stream is encountered.
1883 *
1884 * @param dest array to hold values
1885 * @param off offset for array
1886 * @param len max number of bytes to read into array
1887 * @return bytes read into array or -1 if end of stream is encountered.
1888 * @since 1.3
1889 */
1890 @Override
1891 public int read(byte[] dest, int off, int len)
1892 throws java.io.IOException {
1893 int i;
1894 int b;
1895 for (i = 0; i < len; i++) {
1896 b = read();
1897
1898 if (b >= 0) {
1899 dest[off + i] = (byte) b;
1900 } else if (i == 0) {
1901 return -1;
1902 } else {
1903 break; // Out of 'for' loop
1904 } // Out of 'for' loop
1905 } // end for: each byte read
1906 return i;
1907 } // end read
1908
1909 } // end inner class InputStream
1910
1911
1912
1913
1914
1915
1916 /* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */
1917
1918
1919 /**
1920 * A {@link Base64.OutputStream} will write data to another
1921 * <tt>java.io.OutputStream</tt>, given in the constructor,
1922 * and encode/decode to/from Base64 notation on the fly.
1923 *
1924 * @see Base64
1925 * @since 1.3
1926 */
1927 public static class OutputStream extends java.io.FilterOutputStream {
1928
1929 private boolean encode;
1930 private int position;
1931 private byte[] buffer;
1932 private int bufferLength;
1933 private int lineLength;
1934 private boolean breakLines;
1935 private byte[] b4; // Scratch used in a few places
1936 private boolean suspendEncoding;
1937 private int options; // Record for later
1938 private byte[] decodabet; // Local copies to avoid extra method calls
1939
1940 /**
1941 * Constructs a {@link Base64.OutputStream} in ENCODE mode.
1942 *
1943 * @param out the <tt>java.io.OutputStream</tt> to which data will be written.
1944 * @since 1.3
1945 */
1946 public OutputStream(java.io.OutputStream out) {
1947 this(out, ENCODE);
1948 } // end constructor
1949
1950
1951 /**
1952 * Constructs a {@link Base64.OutputStream} in
1953 * either ENCODE or DECODE mode.
1954 *
1955 * Valid options:<pre>
1956 * ENCODE or DECODE: Encode or Decode as data is read.
1957 * DO_BREAK_LINES: don't break lines at 76 characters
1958 * (only meaningful when encoding)</i>
1959 * </pre>
1960 *
1961 * Example: <code>new Base64.OutputStream( out, Base64.ENCODE )</code>
1962 *
1963 * @param out the <tt>java.io.OutputStream</tt> to which data will be written.
1964 * @param options Specified options.
1965 * @see Base64#ENCODE
1966 * @see Base64#DECODE
1967 * @see Base64#DO_BREAK_LINES
1968 * @since 1.3
1969 */
1970 public OutputStream(java.io.OutputStream out, int options) {
1971 super(out);
1972 this.breakLines = (options & DO_BREAK_LINES) != 0;
1973 this.encode = (options & ENCODE) != 0;
1974 this.bufferLength = encode ? 3 : 4;
1975 this.buffer = new byte[bufferLength];
1976 this.position = 0;
1977 this.lineLength = 0;
1978 this.suspendEncoding = false;
1979 this.b4 = new byte[4];
1980 this.options = options;
1981 this.decodabet = getDecodabet(options);
1982 } // end constructor
1983
1984
1985 /**
1986 * Writes the byte to the output stream after
1987 * converting to/from Base64 notation.
1988 * When encoding, bytes are buffered three
1989 * at a time before the output stream actually
1990 * gets a write() call.
1991 * When decoding, bytes are buffered four
1992 * at a time.
1993 *
1994 * @param theByte the byte to write
1995 * @since 1.3
1996 */
1997 @Override
1998 public void write(int theByte)
1999 throws java.io.IOException {
2000 // Encoding suspended?
2001 if (suspendEncoding) {
2002 this.out.write(theByte);
2003 return;
2004 } // end if: supsended
2005
2006 // Encode?
2007 if (encode) {
2008 buffer[position++] = (byte) theByte;
2009 if (position >= bufferLength) { // Enough to encode.
2010
2011 this.out.write(encode3to4(b4, buffer, bufferLength, options));
2012
2013 lineLength += 4;
2014 if (breakLines && lineLength >= MAX_LINE_LENGTH) {
2015 this.out.write(NEW_LINE);
2016 lineLength = 0;
2017 } // end if: end of line
2018
2019 position = 0;
2020 } // end if: enough to output
2021 } // end if: encoding
2022
2023 // Else, Decoding
2024 else {
2025 // Meaningful Base64 character?
2026 if (decodabet[theByte & 0x7f] > WHITE_SPACE_ENC) {
2027 buffer[position++] = (byte) theByte;
2028 if (position >= bufferLength) { // Enough to output.
2029
2030 int len = Base64.decode4to3(buffer, 0, b4, 0, options);
2031 out.write(b4, 0, len);
2032 position = 0;
2033 } // end if: enough to output
2034 } // end if: meaningful base64 character
2035 else if (decodabet[theByte & 0x7f] != WHITE_SPACE_ENC) {
2036 throw new java.io.IOException("Invalid character in Base64 data.");
2037 } // end else: not white space either
2038 } // end else: decoding
2039 } // end write
2040
2041
2042 /**
2043 * Calls {@link #write(int)} repeatedly until <var>len</var>
2044 * bytes are written.
2045 *
2046 * @param theBytes array from which to read bytes
2047 * @param off offset for array
2048 * @param len max number of bytes to read into array
2049 * @since 1.3
2050 */
2051 @Override
2052 public void write(byte[] theBytes, int off, int len)
2053 throws java.io.IOException {
2054 // Encoding suspended?
2055 if (suspendEncoding) {
2056 this.out.write(theBytes, off, len);
2057 return;
2058 } // end if: supsended
2059
2060 for (int i = 0; i < len; i++) {
2061 write(theBytes[off + i]);
2062 } // end for: each byte written
2063
2064 } // end write
2065
2066
2067 /**
2068 * Method added by PHIL. [Thanks, PHIL. -Rob]
2069 * This pads the buffer without closing the stream.
2070 *
2071 * @throws java.io.IOException if there's an error.
2072 */
2073 public void flushBase64() throws java.io.IOException {
2074 if (position > 0) {
2075 if (encode) {
2076 out.write(encode3to4(b4, buffer, position, options));
2077 position = 0;
2078 } // end if: encoding
2079 else {
2080 throw new java.io.IOException("Base64 input not properly padded.");
2081 } // end else: decoding
2082 } // end if: buffer partially full
2083
2084 } // end flush
2085
2086
2087 /**
2088 * Flushes and closes (I think, in the superclass) the stream.
2089 *
2090 * @since 1.3
2091 */
2092 @Override
2093 public void close() throws java.io.IOException {
2094 // 1. Ensure that pending characters are written
2095 flushBase64();
2096
2097 // 2. Actually close the stream
2098 // Base class both flushes and closes.
2099 super.close();
2100
2101 buffer = null;
2102 out = null;
2103 } // end close
2104
2105
2106 /**
2107 * Suspends encoding of the stream.
2108 * May be helpful if you need to embed a piece of
2109 * base64-encoded data in a stream.
2110 *
2111 * @throws java.io.IOException if there's an error flushing
2112 * @since 1.5.1
2113 */
2114 public void suspendEncoding() throws java.io.IOException {
2115 flushBase64();
2116 this.suspendEncoding = true;
2117 } // end suspendEncoding
2118
2119
2120 /**
2121 * Resumes encoding of the stream.
2122 * May be helpful if you need to embed a piece of
2123 * base64-encoded data in a stream.
2124 *
2125 * @since 1.5.1
2126 */
2127 public void resumeEncoding() {
2128 this.suspendEncoding = false;
2129 } // end resumeEncoding
2130
2131
2132 } // end inner class OutputStream
2133
2134
2135 } // end class Base64