PageRenderTime 74ms CodeModel.GetById 21ms RepoModel.GetById 2ms app.codeStats 0ms

/razpub/src/com/razie/pub/util/Base64.java

http://razpub.googlecode.com/
Java | 1484 lines | 598 code | 207 blank | 679 comment | 81 complexity | 0780a32f96951b7765d039b8146f5d90 MD5 | raw file
Possible License(s): CC-BY-3.0
  1. package com.razie.pub.util;
  2. /**
  3. * <p>Encodes and decodes to and from Base64 notation.</p>
  4. * <p>Homepage: <a href="http://iharder.net/base64">http://iharder.net/base64</a>.</p>
  5. *
  6. * <p>Example:</p>
  7. *
  8. * <code>String encoded = Base64.encode( myByteArray );</code>
  9. * <br />
  10. * <code>byte[] myByteArray = Base64.decode( encoded );</code>
  11. *
  12. * <p>The <tt>options</tt> parameter, which appears in a few places, is used to pass
  13. * several pieces of information to the encoder. In the "higher level" methods such as
  14. * encodeBytes( bytes, options ) the options parameter can be used to indicate such
  15. * things as first gzipping the bytes before encoding them, not inserting linefeeds,
  16. * and encoding using the URL-safe and Ordered dialects.</p>
  17. *
  18. * <p>Note, according to <a href="http://www.faqs.org/rfcs/rfc3548.html">RFC3548</a>,
  19. * Section 2.1, implementations should not add line feeds unless explicitly told
  20. * to do so. I've got Base64 set to this behavior now, although earlier versions
  21. * broke lines by default.</p>
  22. *
  23. * <p>The constants defined in Base64 can be OR-ed together to combine options, so you
  24. * might make a call like this:</p>
  25. *
  26. * <code>String encoded = Base64.encodeBytes( mybytes, Base64.GZIP | Base64.DO_BREAK_LINES );</code>
  27. * <p>to compress the data before encoding it and then making the output have newline characters.</p>
  28. * <p>Also...</p>
  29. * <code>String encoded = Base64.encodeBytes( crazyString.getBytes() );</code>
  30. *
  31. *
  32. *
  33. * <p>
  34. * Change Log:
  35. * </p>
  36. * <ul>
  37. * <li>v2.3.4 - Fixed bug when working with gzipped streams whereby flushing
  38. * the Base64.OutputStream closed the Base64 encoding (by padding with equals
  39. * signs) too soon. Also added an option to suppress the automatic decoding
  40. * of gzipped streams. Also added experimental support for specifying a
  41. * class loader when using the
  42. * {@link #decodeToObject(java.lang.String, int, java.lang.ClassLoader)}
  43. * method.</li>
  44. * <li>v2.3.3 - Changed default char encoding to US-ASCII which reduces the internal Java
  45. * footprint with its CharEncoders and so forth. Fixed some javadocs that were
  46. * inconsistent. Removed imports and specified things like java.io.IOException
  47. * explicitly inline.</li>
  48. * <li>v2.3.2 - Reduced memory footprint! Finally refined the "guessing" of how big the
  49. * final encoded data will be so that the code doesn't have to create two output
  50. * arrays: an oversized initial one and then a final, exact-sized one. Big win
  51. * when using the {@link #encodeBytesToBytes(byte[])} family of methods (and not
  52. * using the gzip options which uses a different mechanism with streams and stuff).</li>
  53. * <li>v2.3.1 - Added {@link #encodeBytesToBytes(byte[], int, int, int)} and some
  54. * similar helper methods to be more efficient with memory by not returning a
  55. * String but just a byte array.</li>
  56. * <li>v2.3 - <strong>This is not a drop-in replacement!</strong> This is two years of comments
  57. * and bug fixes queued up and finally executed. Thanks to everyone who sent
  58. * me stuff, and I'm sorry I wasn't able to distribute your fixes to everyone else.
  59. * Much bad coding was cleaned up including throwing exceptions where necessary
  60. * instead of returning null values or something similar. Here are some changes
  61. * that may affect you:
  62. * <ul>
  63. * <li><em>Does not break lines, by default.</em> This is to keep in compliance with
  64. * <a href="http://www.faqs.org/rfcs/rfc3548.html">RFC3548</a>.</li>
  65. * <li><em>Throws exceptions instead of returning null values.</em> Because some operations
  66. * (especially those that may permit the GZIP option) use IO streams, there
  67. * is a possiblity of an java.io.IOException being thrown. After some discussion and
  68. * thought, I've changed the behavior of the methods to throw java.io.IOExceptions
  69. * rather than return null if ever there's an error. I think this is more
  70. * appropriate, though it will require some changes to your code. Sorry,
  71. * it should have been done this way to begin with.</li>
  72. * <li><em>Removed all references to System.out, System.err, and the like.</em>
  73. * Shame on me. All I can say is sorry they were ever there.</li>
  74. * <li><em>Throws NullPointerExceptions and IllegalArgumentExceptions</em> as needed
  75. * such as when passed arrays are null or offsets are invalid.</li>
  76. * <li>Cleaned up as much javadoc as I could to avoid any javadoc warnings.
  77. * This was especially annoying before for people who were thorough in their
  78. * own projects and then had gobs of javadoc warnings on this file.</li>
  79. * </ul>
  80. * <li>v2.2.1 - Fixed bug using URL_SAFE and ORDERED encodings. Fixed bug
  81. * when using very small files (~< 40 bytes).</li>
  82. * <li>v2.2 - Added some helper methods for encoding/decoding directly from
  83. * one file to the next. Also added a main() method to support command line
  84. * encoding/decoding from one file to the next. Also added these Base64 dialects:
  85. * <ol>
  86. * <li>The default is RFC3548 format.</li>
  87. * <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.URLSAFE_FORMAT) generates
  88. * URL and file name friendly format as described in Section 4 of RFC3548.
  89. * http://www.faqs.org/rfcs/rfc3548.html</li>
  90. * <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.ORDERED_FORMAT) generates
  91. * URL and file name friendly format that preserves lexical ordering as described
  92. * in http://www.faqs.org/qa/rfcc-1940.html</li>
  93. * </ol>
  94. * Special thanks to Jim Kellerman at <a href="http://www.powerset.com/">http://www.powerset.com/</a>
  95. * for contributing the new Base64 dialects.
  96. * </li>
  97. *
  98. * <li>v2.1 - Cleaned up javadoc comments and unused variables and methods. Added
  99. * some convenience methods for reading and writing to and from files.</li>
  100. * <li>v2.0.2 - Now specifies UTF-8 encoding in places where the code fails on systems
  101. * with other encodings (like EBCDIC).</li>
  102. * <li>v2.0.1 - Fixed an error when decoding a single byte, that is, when the
  103. * encoded data was a single byte.</li>
  104. * <li>v2.0 - I got rid of methods that used booleans to set options.
  105. * Now everything is more consolidated and cleaner. The code now detects
  106. * when data that's being decoded is gzip-compressed and will decompress it
  107. * automatically. Generally things are cleaner. You'll probably have to
  108. * change some method calls that you were making to support the new
  109. * options format (<tt>int</tt>s that you "OR" together).</li>
  110. * <li>v1.5.1 - Fixed bug when decompressing and decoding to a
  111. * byte[] using <tt>decode( String s, boolean gzipCompressed )</tt>.
  112. * Added the ability to "suspend" encoding in the Output Stream so
  113. * you can turn on and off the encoding if you need to embed base64
  114. * data in an otherwise "normal" stream (like an XML file).</li>
  115. * <li>v1.5 - Output stream pases on flush() command but doesn't do anything itself.
  116. * This helps when using GZIP streams.
  117. * Added the ability to GZip-compress objects before encoding them.</li>
  118. * <li>v1.4 - Added helper methods to read/write files.</li>
  119. * <li>v1.3.6 - Fixed OutputStream.flush() so that 'position' is reset.</li>
  120. * <li>v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in input stream
  121. * where last buffer being read, if not completely full, was not returned.</li>
  122. * <li>v1.3.4 - Fixed when "improperly padded stream" error was thrown at the wrong time.</li>
  123. * <li>v1.3.3 - Fixed I/O streams which were totally messed up.</li>
  124. * </ul>
  125. *
  126. * <p>
  127. * I am placing this code in the Public Domain. Do with it as you will.
  128. * This software comes with no guarantees or warranties but with
  129. * plenty of well-wishing instead!
  130. * Please visit <a href="http://iharder.net/base64">http://iharder.net/base64</a>
  131. * periodically to check for updates or to contribute improvements.
  132. * </p>
  133. *
  134. * @author Robert Harder
  135. * @author rob@iharder.net
  136. * @version 2.3.3
  137. */
  138. public class Base64
  139. {
  140. /* ******** P U B L I C F I E L D S ******** */
  141. /** No options specified. Value is zero. */
  142. public final static int NO_OPTIONS = 0;
  143. /** Specify encoding in first bit. Value is one. */
  144. public final static int ENCODE = 1;
  145. /** Specify decoding in first bit. Value is zero. */
  146. public final static int DECODE = 0;
  147. /** Specify that data should be gzip-compressed in second bit. Value is two. */
  148. public final static int GZIP = 2;
  149. /** Specify that gzipped data should <em>not</em> be automatically gunzipped. */
  150. public final static int DONT_GUNZIP = 4;
  151. /** Do break lines when encoding. Value is 8. */
  152. public final static int DO_BREAK_LINES = 8;
  153. /**
  154. * Encode using Base64-like encoding that is URL- and Filename-safe as described
  155. * in Section 4 of RFC3548:
  156. * <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>.
  157. * It is important to note that data encoded this way is <em>not</em> officially valid Base64,
  158. * or at the very least should not be called Base64 without also specifying that is
  159. * was encoded using the URL- and Filename-safe dialect.
  160. */
  161. public final static int URL_SAFE = 16;
  162. /**
  163. * Encode using the special "ordered" dialect of Base64 described here:
  164. * <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>.
  165. */
  166. public final static int ORDERED = 32;
  167. /* ******** P R I V A T E F I E L D S ******** */
  168. /** Maximum line length (76) of Base64 output. */
  169. private final static int MAX_LINE_LENGTH = 76;
  170. /** The equals sign (=) as a byte. */
  171. private final static byte EQUALS_SIGN = (byte)'=';
  172. /** The new line character (\n) as a byte. */
  173. private final static byte NEW_LINE = (byte)'\n';
  174. /** Preferred encoding. */
  175. private final static String PREFERRED_ENCODING = "US-ASCII";
  176. private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding
  177. private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding
  178. /* ******** S T A N D A R D B A S E 6 4 A L P H A B E T ******** */
  179. /** The 64 valid Base64 values. */
  180. /* Host platform me be something funny like EBCDIC, so we hardcode these values. */
  181. private final static byte[] _STANDARD_ALPHABET = {
  182. (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
  183. (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
  184. (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
  185. (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
  186. (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
  187. (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
  188. (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
  189. (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z',
  190. (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5',
  191. (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/'
  192. };
  193. /**
  194. * Translates a Base64 value to either its 6-bit reconstruction value
  195. * or a negative number indicating some other meaning.
  196. **/
  197. private final static byte[] _STANDARD_DECODABET = {
  198. -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8
  199. -5,-5, // Whitespace: Tab and Linefeed
  200. -9,-9, // Decimal 11 - 12
  201. -5, // Whitespace: Carriage Return
  202. -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26
  203. -9,-9,-9,-9,-9, // Decimal 27 - 31
  204. -5, // Whitespace: Space
  205. -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42
  206. 62, // Plus sign at decimal 43
  207. -9,-9,-9, // Decimal 44 - 46
  208. 63, // Slash at decimal 47
  209. 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine
  210. -9,-9,-9, // Decimal 58 - 60
  211. -1, // Equals sign at decimal 61
  212. -9,-9,-9, // Decimal 62 - 64
  213. 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N'
  214. 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z'
  215. -9,-9,-9,-9,-9,-9, // Decimal 91 - 96
  216. 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm'
  217. 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z'
  218. -9,-9,-9,-9 // Decimal 123 - 126
  219. /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139
  220. -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
  221. -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
  222. -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
  223. -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
  224. -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
  225. -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
  226. -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
  227. -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
  228. -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */
  229. };
  230. /* ******** U R L S A F E B A S E 6 4 A L P H A B E T ******** */
  231. /**
  232. * Used in the URL- and Filename-safe dialect described in Section 4 of RFC3548:
  233. * <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>.
  234. * Notice that the last two bytes become "hyphen" and "underscore" instead of "plus" and "slash."
  235. */
  236. private final static byte[] _URL_SAFE_ALPHABET = {
  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)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
  242. (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
  243. (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
  244. (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z',
  245. (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5',
  246. (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'-', (byte)'_'
  247. };
  248. /**
  249. * Used in decoding URL- and Filename-safe dialects of Base64.
  250. */
  251. private final static byte[] _URL_SAFE_DECODABET = {
  252. -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8
  253. -5,-5, // Whitespace: Tab and Linefeed
  254. -9,-9, // Decimal 11 - 12
  255. -5, // Whitespace: Carriage Return
  256. -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26
  257. -9,-9,-9,-9,-9, // Decimal 27 - 31
  258. -5, // Whitespace: Space
  259. -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42
  260. -9, // Plus sign at decimal 43
  261. -9, // Decimal 44
  262. 62, // Minus sign at decimal 45
  263. -9, // Decimal 46
  264. -9, // Slash at decimal 47
  265. 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine
  266. -9,-9,-9, // Decimal 58 - 60
  267. -1, // Equals sign at decimal 61
  268. -9,-9,-9, // Decimal 62 - 64
  269. 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N'
  270. 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z'
  271. -9,-9,-9,-9, // Decimal 91 - 94
  272. 63, // Underscore at decimal 95
  273. -9, // Decimal 96
  274. 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm'
  275. 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z'
  276. -9,-9,-9,-9 // Decimal 123 - 126
  277. /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139
  278. -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
  279. -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
  280. -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
  281. -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
  282. -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
  283. -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
  284. -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
  285. -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
  286. -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */
  287. };
  288. /* ******** O R D E R E D B A S E 6 4 A L P H A B E T ******** */
  289. /**
  290. * I don't get the point of this technique, but someone requested it,
  291. * and it is described here:
  292. * <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>.
  293. */
  294. private final static byte[] _ORDERED_ALPHABET = {
  295. (byte)'-',
  296. (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4',
  297. (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9',
  298. (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
  299. (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
  300. (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
  301. (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
  302. (byte)'_',
  303. (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
  304. (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
  305. (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
  306. (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z'
  307. };
  308. /**
  309. * Used in decoding the "ordered" dialect of Base64.
  310. */
  311. private final static byte[] _ORDERED_DECODABET = {
  312. -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8
  313. -5,-5, // Whitespace: Tab and Linefeed
  314. -9,-9, // Decimal 11 - 12
  315. -5, // Whitespace: Carriage Return
  316. -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26
  317. -9,-9,-9,-9,-9, // Decimal 27 - 31
  318. -5, // Whitespace: Space
  319. -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42
  320. -9, // Plus sign at decimal 43
  321. -9, // Decimal 44
  322. 0, // Minus sign at decimal 45
  323. -9, // Decimal 46
  324. -9, // Slash at decimal 47
  325. 1,2,3,4,5,6,7,8,9,10, // Numbers zero through nine
  326. -9,-9,-9, // Decimal 58 - 60
  327. -1, // Equals sign at decimal 61
  328. -9,-9,-9, // Decimal 62 - 64
  329. 11,12,13,14,15,16,17,18,19,20,21,22,23, // Letters 'A' through 'M'
  330. 24,25,26,27,28,29,30,31,32,33,34,35,36, // Letters 'N' through 'Z'
  331. -9,-9,-9,-9, // Decimal 91 - 94
  332. 37, // Underscore at decimal 95
  333. -9, // Decimal 96
  334. 38,39,40,41,42,43,44,45,46,47,48,49,50, // Letters 'a' through 'm'
  335. 51,52,53,54,55,56,57,58,59,60,61,62,63, // Letters 'n' through 'z'
  336. -9,-9,-9,-9 // Decimal 123 - 126
  337. /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139
  338. -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
  339. -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
  340. -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
  341. -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
  342. -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
  343. -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
  344. -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
  345. -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
  346. -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */
  347. };
  348. /* ******** D E T E R M I N E W H I C H A L H A B E T ******** */
  349. /**
  350. * Returns one of the _SOMETHING_ALPHABET byte arrays depending on
  351. * the options specified.
  352. * It's possible, though silly, to specify ORDERED <b>and</b> URLSAFE
  353. * in which case one of them will be picked, though there is
  354. * no guarantee as to which one will be picked.
  355. */
  356. private final static byte[] getAlphabet( int options ) {
  357. if ((options & URL_SAFE) == URL_SAFE) {
  358. return _URL_SAFE_ALPHABET;
  359. } else if ((options & ORDERED) == ORDERED) {
  360. return _ORDERED_ALPHABET;
  361. } else {
  362. return _STANDARD_ALPHABET;
  363. }
  364. } // end getAlphabet
  365. /**
  366. * Returns one of the _SOMETHING_DECODABET byte arrays depending on
  367. * the options specified.
  368. * It's possible, though silly, to specify ORDERED and URL_SAFE
  369. * in which case one of them will be picked, though there is
  370. * no guarantee as to which one will be picked.
  371. */
  372. private final static byte[] getDecodabet( int options ) {
  373. if( (options & URL_SAFE) == URL_SAFE) {
  374. return _URL_SAFE_DECODABET;
  375. } else if ((options & ORDERED) == ORDERED) {
  376. return _ORDERED_DECODABET;
  377. } else {
  378. return _STANDARD_DECODABET;
  379. }
  380. } // end getAlphabet
  381. /** Defeats instantiation. */
  382. private Base64(){}
  383. /* ******** E N C O D I N G M E T H O D S ******** */
  384. /**
  385. * Encodes up to the first three bytes of array <var>threeBytes</var>
  386. * and returns a four-byte array in Base64 notation.
  387. * The actual number of significant bytes in your array is
  388. * given by <var>numSigBytes</var>.
  389. * The array <var>threeBytes</var> needs only be as big as
  390. * <var>numSigBytes</var>.
  391. * Code can reuse a byte array by passing a four-byte array as <var>b4</var>.
  392. *
  393. * @param b4 A reusable byte array to reduce array instantiation
  394. * @param threeBytes the array to convert
  395. * @param numSigBytes the number of significant bytes in your array
  396. * @return four byte array in Base64 notation.
  397. * @since 1.5.1
  398. */
  399. private static byte[] encode3to4( byte[] b4, byte[] threeBytes, int numSigBytes, int options ) {
  400. encode3to4( threeBytes, 0, numSigBytes, b4, 0, options );
  401. return b4;
  402. } // end encode3to4
  403. /**
  404. * <p>Encodes up to three bytes of the array <var>source</var>
  405. * and writes the resulting four Base64 bytes to <var>destination</var>.
  406. * The source and destination arrays can be manipulated
  407. * anywhere along their length by specifying
  408. * <var>srcOffset</var> and <var>destOffset</var>.
  409. * This method does not check to make sure your arrays
  410. * are large enough to accomodate <var>srcOffset</var> + 3 for
  411. * the <var>source</var> array or <var>destOffset</var> + 4 for
  412. * the <var>destination</var> array.
  413. * The actual number of significant bytes in your array is
  414. * given by <var>numSigBytes</var>.</p>
  415. * <p>This is the lowest level of the encoding methods with
  416. * all possible parameters.</p>
  417. *
  418. * @param source the array to convert
  419. * @param srcOffset the index where conversion begins
  420. * @param numSigBytes the number of significant bytes in your array
  421. * @param destination the array to hold the conversion
  422. * @param destOffset the index where output will be put
  423. * @return the <var>destination</var> array
  424. * @since 1.3
  425. */
  426. private static byte[] encode3to4(
  427. byte[] source, int srcOffset, int numSigBytes,
  428. byte[] destination, int destOffset, int options ) {
  429. byte[] ALPHABET = getAlphabet( options );
  430. // 1 2 3
  431. // 01234567890123456789012345678901 Bit position
  432. // --------000000001111111122222222 Array position from threeBytes
  433. // --------| || || || | Six bit groups to index ALPHABET
  434. // >>18 >>12 >> 6 >> 0 Right shift necessary
  435. // 0x3f 0x3f 0x3f Additional AND
  436. // Create buffer with zero-padding if there are only one or two
  437. // significant bytes passed in the array.
  438. // We have to shift left 24 in order to flush out the 1's that appear
  439. // when Java treats a value as negative that is cast from a byte to an int.
  440. int inBuff = ( numSigBytes > 0 ? ((source[ srcOffset ] << 24) >>> 8) : 0 )
  441. | ( numSigBytes > 1 ? ((source[ srcOffset + 1 ] << 24) >>> 16) : 0 )
  442. | ( numSigBytes > 2 ? ((source[ srcOffset + 2 ] << 24) >>> 24) : 0 );
  443. switch( numSigBytes )
  444. {
  445. case 3:
  446. destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
  447. destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
  448. destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ];
  449. destination[ destOffset + 3 ] = ALPHABET[ (inBuff ) & 0x3f ];
  450. return destination;
  451. case 2:
  452. destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
  453. destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
  454. destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ];
  455. destination[ destOffset + 3 ] = EQUALS_SIGN;
  456. return destination;
  457. case 1:
  458. destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
  459. destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
  460. destination[ destOffset + 2 ] = EQUALS_SIGN;
  461. destination[ destOffset + 3 ] = EQUALS_SIGN;
  462. return destination;
  463. default:
  464. return destination;
  465. } // end switch
  466. } // end encode3to4
  467. /**
  468. * Performs Base64 encoding on the <code>raw</code> ByteBuffer,
  469. * writing it to the <code>encoded</code> ByteBuffer.
  470. * This is an experimental feature. Currently it does not
  471. * pass along any options (such as {@link #DO_BREAK_LINES}
  472. * or {@link #GZIP}.
  473. *
  474. * @param raw input buffer
  475. * @param encoded output buffer
  476. * @since 2.3
  477. */
  478. public static void encode( java.nio.ByteBuffer raw, java.nio.ByteBuffer encoded ){
  479. byte[] raw3 = new byte[3];
  480. byte[] enc4 = new byte[4];
  481. while( raw.hasRemaining() ){
  482. int rem = Math.min(3,raw.remaining());
  483. raw.get(raw3,0,rem);
  484. Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS );
  485. encoded.put(enc4);
  486. } // end input remaining
  487. }
  488. /**
  489. * Performs Base64 encoding on the <code>raw</code> ByteBuffer,
  490. * writing it to the <code>encoded</code> CharBuffer.
  491. * This is an experimental feature. Currently it does not
  492. * pass along any options (such as {@link #DO_BREAK_LINES}
  493. * or {@link #GZIP}.
  494. *
  495. * @param raw input buffer
  496. * @param encoded output buffer
  497. * @since 2.3
  498. */
  499. public static void encode( java.nio.ByteBuffer raw, java.nio.CharBuffer encoded ){
  500. byte[] raw3 = new byte[3];
  501. byte[] enc4 = new byte[4];
  502. while( raw.hasRemaining() ){
  503. int rem = Math.min(3,raw.remaining());
  504. raw.get(raw3,0,rem);
  505. Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS );
  506. for( int i = 0; i < 4; i++ ){
  507. encoded.put( (char)(enc4[i] & 0xFF) );
  508. }
  509. } // end input remaining
  510. }
  511. /**
  512. * Serializes an object and returns the Base64-encoded
  513. * version of that serialized object.
  514. *
  515. * <p>As of v 2.3, if the object
  516. * cannot be serialized or there is another error,
  517. * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
  518. * In earlier versions, it just returned a null value, but
  519. * in retrospect that's a pretty poor way to handle it.</p>
  520. *
  521. * The object is not GZip-compressed before being encoded.
  522. *
  523. * @param serializableObject The object to encode
  524. * @return The Base64-encoded object
  525. * @throws java.io.IOException if there is an error
  526. * @throws NullPointerException if serializedObject is null
  527. * @since 1.4
  528. */
  529. public static String encodeObject( java.io.Serializable serializableObject )
  530. throws java.io.IOException {
  531. return encodeObject( serializableObject, NO_OPTIONS );
  532. } // end encodeObject
  533. /**
  534. * Serializes an object and returns the Base64-encoded
  535. * version of that serialized object.
  536. *
  537. * <p>As of v 2.3, if the object
  538. * cannot be serialized or there is another error,
  539. * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
  540. * In earlier versions, it just returned a null value, but
  541. * in retrospect that's a pretty poor way to handle it.</p>
  542. *
  543. * The object is not GZip-compressed before being encoded.
  544. * <p>
  545. * Example options:<pre>
  546. * GZIP: gzip-compresses object before encoding it.
  547. * DO_BREAK_LINES: break lines at 76 characters
  548. * </pre>
  549. * <p>
  550. * Example: <code>encodeObject( myObj, Base64.GZIP )</code> or
  551. * <p>
  552. * Example: <code>encodeObject( myObj, Base64.GZIP | Base64.DO_BREAK_LINES )</code>
  553. *
  554. * @param serializableObject The object to encode
  555. * @param options Specified options
  556. * @return The Base64-encoded object
  557. * @see Base64#GZIP
  558. * @see Base64#DO_BREAK_LINES
  559. * @throws java.io.IOException if there is an error
  560. * @since 2.0
  561. */
  562. public static String encodeObject( java.io.Serializable serializableObject, int options )
  563. throws java.io.IOException {
  564. if( serializableObject == null ){
  565. throw new NullPointerException( "Cannot serialize a null object." );
  566. } // end if: null
  567. // Streams
  568. java.io.ByteArrayOutputStream baos = null;
  569. java.io.OutputStream b64os = null;
  570. java.util.zip.GZIPOutputStream gzos = null;
  571. java.io.ObjectOutputStream oos = null;
  572. try {
  573. // ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream
  574. baos = new java.io.ByteArrayOutputStream();
  575. b64os = new Base64.OutputStream( baos, ENCODE | options );
  576. if( (options & GZIP) != 0 ){
  577. // Gzip
  578. gzos = new java.util.zip.GZIPOutputStream(b64os);
  579. oos = new java.io.ObjectOutputStream( gzos );
  580. } else {
  581. // Not gzipped
  582. oos = new java.io.ObjectOutputStream( b64os );
  583. }
  584. oos.writeObject( serializableObject );
  585. } // end try
  586. catch( java.io.IOException e ) {
  587. // Catch it and then throw it immediately so that
  588. // the finally{} block is called for cleanup.
  589. throw e;
  590. } // end catch
  591. finally {
  592. try{ oos.close(); } catch( Exception e ){}
  593. try{ gzos.close(); } catch( Exception e ){}
  594. try{ b64os.close(); } catch( Exception e ){}
  595. try{ baos.close(); } catch( Exception e ){}
  596. } // end finally
  597. // Return value according to relevant encoding.
  598. try {
  599. return new String( baos.toByteArray(), PREFERRED_ENCODING );
  600. } // end try
  601. catch (java.io.UnsupportedEncodingException uue){
  602. // Fall back to some Java default
  603. return new String( baos.toByteArray() );
  604. } // end catch
  605. } // end encode
  606. /**
  607. * Encodes a byte array into Base64 notation.
  608. * Does not GZip-compress data.
  609. *
  610. * @param source The data to convert
  611. * @return The data in Base64-encoded form
  612. * @throws NullPointerException if source array is null
  613. * @since 1.4
  614. */
  615. public static String encodeBytes( byte[] source ) {
  616. // Since we're not going to have the GZIP encoding turned on,
  617. // we're not going to have an java.io.IOException thrown, so
  618. // we should not force the user to have to catch it.
  619. String encoded = null;
  620. try {
  621. encoded = encodeBytes(source, 0, source.length, NO_OPTIONS);
  622. } catch (java.io.IOException ex) {
  623. assert false : ex.getMessage();
  624. } // end catch
  625. assert encoded != null;
  626. return encoded;
  627. } // end encodeBytes
  628. /**
  629. * Encodes a byte array into Base64 notation.
  630. * <p>
  631. * Example options:<pre>
  632. * GZIP: gzip-compresses object before encoding it.
  633. * DO_BREAK_LINES: break lines at 76 characters
  634. * <i>Note: Technically, this makes your encoding non-compliant.</i>
  635. * </pre>
  636. * <p>
  637. * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
  638. * <p>
  639. * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES )</code>
  640. *
  641. *
  642. * <p>As of v 2.3, if there is an error with the GZIP stream,
  643. * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
  644. * In earlier versions, it just returned a null value, but
  645. * in retrospect that's a pretty poor way to handle it.</p>
  646. *
  647. *
  648. * @param source The data to convert
  649. * @param options Specified options
  650. * @return The Base64-encoded data as a String
  651. * @see Base64#GZIP
  652. * @see Base64#DO_BREAK_LINES
  653. * @throws java.io.IOException if there is an error
  654. * @throws NullPointerException if source array is null
  655. * @since 2.0
  656. */
  657. public static String encodeBytes( byte[] source, int options ) throws java.io.IOException {
  658. return encodeBytes( source, 0, source.length, options );
  659. } // end encodeBytes
  660. /**
  661. * Encodes a byte array into Base64 notation.
  662. * Does not GZip-compress data.
  663. *
  664. * <p>As of v 2.3, if there is an error,
  665. * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
  666. * In earlier versions, it just returned a null value, but
  667. * in retrospect that's a pretty poor way to handle it.</p>
  668. *
  669. *
  670. * @param source The data to convert
  671. * @param off Offset in array where conversion should begin
  672. * @param len Length of data to convert
  673. * @return The Base64-encoded data as a String
  674. * @throws NullPointerException if source array is null
  675. * @throws IllegalArgumentException if source array, offset, or length are invalid
  676. * @since 1.4
  677. */
  678. public static String encodeBytes( byte[] source, int off, int len ) {
  679. // Since we're not going to have the GZIP encoding turned on,
  680. // we're not going to have an java.io.IOException thrown, so
  681. // we should not force the user to have to catch it.
  682. String encoded = null;
  683. try {
  684. encoded = encodeBytes( source, off, len, NO_OPTIONS );
  685. } catch (java.io.IOException ex) {
  686. assert false : ex.getMessage();
  687. } // end catch
  688. assert encoded != null;
  689. return encoded;
  690. } // end encodeBytes
  691. /**
  692. * Encodes a byte array into Base64 notation.
  693. * <p>
  694. * Example options:<pre>
  695. * GZIP: gzip-compresses object before encoding it.
  696. * DO_BREAK_LINES: break lines at 76 characters
  697. * <i>Note: Technically, this makes your encoding non-compliant.</i>
  698. * </pre>
  699. * <p>
  700. * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
  701. * <p>
  702. * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES )</code>
  703. *
  704. *
  705. * <p>As of v 2.3, if there is an error with the GZIP stream,
  706. * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
  707. * In earlier versions, it just returned a null value, but
  708. * in retrospect that's a pretty poor way to handle it.</p>
  709. *
  710. *
  711. * @param source The data to convert
  712. * @param off Offset in array where conversion should begin
  713. * @param len Length of data to convert
  714. * @param options Specified options
  715. * @return The Base64-encoded data as a String
  716. * @see Base64#GZIP
  717. * @see Base64#DO_BREAK_LINES
  718. * @throws java.io.IOException if there is an error
  719. * @throws NullPointerException if source array is null
  720. * @throws IllegalArgumentException if source array, offset, or length are invalid
  721. * @since 2.0
  722. */
  723. public static String encodeBytes( byte[] source, int off, int len, int options ) throws java.io.IOException {
  724. byte[] encoded = encodeBytesToBytes( source, off, len, options );
  725. // Return value according to relevant encoding.
  726. try {
  727. return new String( encoded, PREFERRED_ENCODING );
  728. } // end try
  729. catch (java.io.UnsupportedEncodingException uue) {
  730. return new String( encoded );
  731. } // end catch
  732. } // end encodeBytes
  733. /**
  734. * Similar to {@link #encodeBytes(byte[])} but returns
  735. * a byte array instead of instantiating a String. This is more efficient
  736. * if you're working with I/O streams and have large data sets to encode.
  737. *
  738. *
  739. * @param source The data to convert
  740. * @return The Base64-encoded data as a byte[] (of ASCII characters)
  741. * @throws NullPointerException if source array is null
  742. * @since 2.3.1
  743. */
  744. public static byte[] encodeBytesToBytes( byte[] source ) {
  745. byte[] encoded = null;
  746. try {
  747. encoded = encodeBytesToBytes( source, 0, source.length, Base64.NO_OPTIONS );
  748. } catch( java.io.IOException ex ) {
  749. assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage();
  750. }
  751. return encoded;
  752. }
  753. /**
  754. * Similar to {@link #encodeBytes(byte[], int, int, int)} but returns
  755. * a byte array instead of instantiating a String. This is more efficient
  756. * if you're working with I/O streams and have large data sets to encode.
  757. *
  758. *
  759. * @param source The data to convert
  760. * @param off Offset in array where conversion should begin
  761. * @param len Length of data to convert
  762. * @param options Specified options
  763. * @return The Base64-encoded data as a String
  764. * @see Base64#GZIP
  765. * @see Base64#DO_BREAK_LINES
  766. * @throws java.io.IOException if there is an error
  767. * @throws NullPointerException if source array is null
  768. * @throws IllegalArgumentException if source array, offset, or length are invalid
  769. * @since 2.3.1
  770. */
  771. public static byte[] encodeBytesToBytes( byte[] source, int off, int len, int options ) throws java.io.IOException {
  772. if( source == null ){
  773. throw new NullPointerException( "Cannot serialize a null array." );
  774. } // end if: null
  775. if( off < 0 ){
  776. throw new IllegalArgumentException( "Cannot have negative offset: " + off );
  777. } // end if: off < 0
  778. if( len < 0 ){
  779. throw new IllegalArgumentException( "Cannot have length offset: " + len );
  780. } // end if: len < 0
  781. if( off + len > source.length ){
  782. throw new IllegalArgumentException(
  783. String.format( "Cannot have offset of %d and length of %d with array of length %d", off,len,source.length));
  784. } // end if: off < 0
  785. // Compress?
  786. if( (options & GZIP) != 0 ) {
  787. java.io.ByteArrayOutputStream baos = null;
  788. java.util.zip.GZIPOutputStream gzos = null;
  789. Base64.OutputStream b64os = null;
  790. try {
  791. // GZip -> Base64 -> ByteArray
  792. baos = new java.io.ByteArrayOutputStream();
  793. b64os = new Base64.OutputStream( baos, ENCODE | options );
  794. gzos = new java.util.zip.GZIPOutputStream( b64os );
  795. gzos.write( source, off, len );
  796. gzos.close();
  797. } // end try
  798. catch( java.io.IOException e ) {
  799. // Catch it and then throw it immediately so that
  800. // the finally{} block is called for cleanup.
  801. throw e;
  802. } // end catch
  803. finally {
  804. try{ gzos.close(); } catch( Exception e ){}
  805. try{ b64os.close(); } catch( Exception e ){}
  806. try{ baos.close(); } catch( Exception e ){}
  807. } // end finally
  808. return baos.toByteArray();
  809. } // end if: compress
  810. // Else, don't compress. Better not to use streams at all then.
  811. else {
  812. boolean breakLines = (options & DO_BREAK_LINES) > 0;
  813. //int len43 = len * 4 / 3;
  814. //byte[] outBuff = new byte[ ( len43 ) // Main 4:3
  815. // + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding
  816. // + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines
  817. // Try to determine more precisely how big the array needs to be.
  818. // If we get it right, we don't have to do an array copy, and
  819. // we save a bunch of memory.
  820. int encLen = ( len / 3 ) * 4 + ( len % 3 > 0 ? 4 : 0 ); // Bytes needed for actual encoding
  821. if( breakLines ){
  822. encLen += encLen / MAX_LINE_LENGTH; // Plus extra newline characters
  823. }
  824. byte[] outBuff = new byte[ encLen ];
  825. int d = 0;
  826. int e = 0;
  827. int len2 = len - 2;
  828. int lineLength = 0;
  829. for( ; d < len2; d+=3, e+=4 ) {
  830. encode3to4( source, d+off, 3, outBuff, e, options );
  831. lineLength += 4;
  832. if( breakLines && lineLength >= MAX_LINE_LENGTH )
  833. {
  834. outBuff[e+4] = NEW_LINE;
  835. e++;
  836. lineLength = 0;
  837. } // end if: end of line
  838. } // en dfor: each piece of array
  839. if( d < len ) {
  840. encode3to4( source, d+off, len - d, outBuff, e, options );
  841. e += 4;
  842. } // end if: some padding needed
  843. // Only resize array if we didn't guess it right.
  844. if( e < outBuff.length - 1 ){
  845. byte[] finalOut = new byte[e];
  846. System.arraycopy(outBuff,0, finalOut,0,e);
  847. //System.err.println("Having to resize array from " + outBuff.length + " to " + e );
  848. return finalOut;
  849. } else {
  850. //System.err.println("No need to resize array.");
  851. return outBuff;
  852. }
  853. } // end else: don't compress
  854. } // end encodeBytesToBytes
  855. /* ******** D E C O D I N G M E T H O D S ******** */
  856. /**
  857. * Decodes four bytes from array <var>source</var>
  858. * and writes the resulting bytes (up to three of them)
  859. * to <var>destination</var>.
  860. * The source and destination arrays can be manipulated
  861. * anywhere along their length by specifying
  862. * <var>srcOffset</var> and <var>destOffset</var>.
  863. * This method does not check to make sure your arrays
  864. * are large enough to accomodate <var>srcOffset</var> + 4 for
  865. * the <var>source</var> array or <var>destOffset</var> + 3 for
  866. * the <var>destination</var> array.
  867. * This method returns the actual number of bytes that
  868. * were converted from the Base64 encoding.
  869. * <p>This is the lowest level of the decoding methods with
  870. * all possible parameters.</p>
  871. *
  872. *
  873. * @param source the array to convert
  874. * @param srcOffset the index where conversion begins
  875. * @param destination the array to hold the conversion
  876. * @param destOffset the index where output will be put
  877. * @param options alphabet type is pulled from this (standard, url-safe, ordered)
  878. * @return the number of decoded bytes converted
  879. * @throws NullPointerException if source or destination arrays are null
  880. * @throws IllegalArgumentException if srcOffset or destOffset are invalid
  881. * or there is not enough room in the array.
  882. * @since 1.3
  883. */
  884. private static int decode4to3(
  885. byte[] source, int srcOffset,
  886. byte[] destination, int destOffset, int options ) {
  887. // Lots of error checking and exception throwing
  888. if( source == null ){
  889. throw new NullPointerException( "Source array was null." );
  890. } // end if
  891. if( destination == null ){
  892. throw new NullPointerException( "Destination array was null." );
  893. } // end if
  894. if( srcOffset < 0 || srcOffset + 3 >= source.length ){
  895. throw new IllegalArgumentException( String.format(
  896. "Source array with length %d cannot have offset of %d and still process four bytes.", source.length, srcOffset ) );
  897. } // end if
  898. if( destOffset < 0 || destOffset +2 >= destination.length ){
  899. throw new IllegalArgumentException( String.format(
  900. "Destination array with length %d cannot have offset of %d and still store three bytes.", destination.length, destOffset ) );
  901. } // end if
  902. byte[] DECODABET = getDecodabet( options );
  903. // Example: Dk==
  904. if( source[ srcOffset + 2] == EQUALS_SIGN ) {
  905. // Two ways to do the same thing. Don't know which way I like best.
  906. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
  907. // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 );
  908. int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
  909. | ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 );
  910. destination[ destOffset ] = (byte)( outBuff >>> 16 );
  911. return 1;
  912. }
  913. // Example: DkL=
  914. else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) {
  915. // Two ways to do the same thing. Don't know which way I like best.
  916. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
  917. // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
  918. // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 );
  919. int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
  920. | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
  921. | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 );
  922. destination[ destOffset ] = (byte)( outBuff >>> 16 );
  923. destination[ destOffset + 1 ] = (byte)( outBuff >>> 8 );
  924. return 2;
  925. }
  926. // Example: DkLE
  927. else {
  928. // Two ways to do the same thing. Don't know which way I like best.
  929. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
  930. // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
  931. // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 )
  932. // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 );
  933. int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
  934. | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
  935. | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6)
  936. | ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) );
  937. destination[ destOffset ] = (byte)( outBuff >> 16 );
  938. destination[ destOffset + 1 ] = (byte)( outBuff >> 8 );
  939. destination[ destOffset + 2 ] = (byte)( outBuff );
  940. return 3;
  941. }
  942. } // end decodeToBytes
  943. /**
  944. * Low-level access to decoding ASCII characters in
  945. * the form of a byte array. <strong>Ignores GUNZIP option, if
  946. * it's set.</strong> This is not generally a recommended method,
  947. * although it is used internally as part of the decoding process.
  948. * Special case: if len = 0, an empty array is returned. Still,
  949. * if you need more speed and reduced memory footprint (and aren't
  950. * gzipping), consider this method.
  951. *
  952. * @param source The Base64 encoded data
  953. * @return decoded data
  954. * @since 2.3.1
  955. */
  956. public static byte[] decode( byte[] source ){
  957. byte[] decoded = null;
  958. try {
  959. decoded = decode( source, 0, source.length, Base64.NO_OPTIONS );
  960. } catch( java.io.IOException ex ) {
  961. assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage();
  962. }
  963. return decoded;
  964. }
  965. /**
  966. * Low-level access to decoding ASCII characters in
  967. * the form of a byte array. <strong>Ignores GUNZIP option, if
  968. * it's set.</strong> This is not generally a recommended method,
  969. * although it is used internally as part of the decoding process.
  970. * Special case: if len = 0, an empty array is returned. Still,
  971. * if you need more speed and reduced memory footprint (and aren't
  972. * gzipping), consider this method.
  973. *
  974. * @param source The Base64 encoded data
  975. * @param off The offset of where to begin decoding
  976. * @param len The length of characters to decode
  977. * @param options Can specify options such as alphabet type to use
  978. * @return decoded data
  979. * @throws java.io.IOException If bogus characters exist in source data
  980. * @since 1.3
  981. */
  982. public static byte[] decode( byte[] source, int off, int len, int options )
  983. throws java.io.IOException {
  984. // Lots of error checking and exception throwing
  985. if( source == null ){
  986. throw new NullPointerException( "Cannot decode null source array." );
  987. } // end if
  988. if( off < 0 || off + len > source.length ){
  989. throw new IllegalArgumentException( String.format(
  990. "Source array with length %d cannot have offset of %d and process %d bytes.", source.length, off, len ) );
  991. } // end if
  992. if( len == 0 ){
  993. return new byte[0];
  994. }else if( len < 4 ){
  995. throw new IllegalArgumentException(
  996. "Base64-encoded string must have at least four characters, but length specified was " + len );
  997. } // end if
  998. byte[] DECODABET = getDecodabet( options );
  999. int len34 = len * 3 / 4; // Estimate on array size
  1000. byte[] outBuff = new byte[ len34 ]; // Upper limit on size of output
  1001. int outBuffPosn = 0; // Keep track of where we're writing
  1002. byte[] b4 = new byte[4]; // Four byte buffer from source, eliminating white space
  1003. int b4Posn = 0; // Keep track of four byte input buffer
  1004. int i = 0; // Source array counter
  1005. byte sbiCrop = 0; // Low seven bits (ASCII) of input
  1006. byte sbiDecode = 0; // Special value from DECODABET
  1007. for( i = off; i < off+len; i++ ) { // Loop through source
  1008. sbiCrop = (byte)(source[i] & 0x7f); // Only the low seven bits
  1009. sbiDecode = DECODABET[ sbiCrop ]; // Special value
  1010. // White space, Equals sign, or legit Base64 character
  1011. // Note the values such as -5 and -9 in the
  1012. // DECODABETs at the top of the file.
  1013. if( sbiDecode >= WHITE_SPACE_ENC ) {
  1014. if( sbiDecode >= EQUALS_SIGN_ENC ) {
  1015. b4[ b4Posn++ ] = sbiCrop; // Save non-whitespace
  1016. if( b4Posn > 3 ) { // Time to decode?
  1017. outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn, options );
  1018. b4Posn = 0;
  1019. // If that was the equals sign, break out of 'for' loop
  1020. if( sbiCrop == EQUALS_SIGN ) {
  1021. break;
  1022. } // end if: equals sign
  1023. } // end if: quartet built
  1024. } // end if: equals sign or better
  1025. } // end if: white space, equals sign or better
  1026. else {
  1027. // There's a bad input character in the Base64 stream.
  1028. throw new java.io.IOException( String.format(
  1029. "Bad Base64 input character '%c' in array position %d", source[i], i ) );
  1030. } // end else:
  1031. } // each input character
  1032. byte[] out = new byte[ outBuffPosn ];
  1033. System.arraycopy( outBuff, 0, out, 0, outBuffPosn );
  1034. return out;
  1035. } // end decode
  1036. /**
  1037. * Decodes data from Base64 notation, automatically
  1038. * detecting gzip-compressed data and decompressing it.
  1039. *
  1040. * @param s the string to decode
  1041. * @return the decoded data
  1042. * @throws java.io.IOException If there is a problem
  1043. * @since 1.4
  1044. */
  1045. public static byte[] decode( String s ) throws java.io.IOException {
  1046. return decode( s, NO_OPTIONS );
  1047. }
  1048. /**
  1049. * Decodes data from Base64 notation, automatically
  1050. * detecting gzip-compressed data and decompressing it.
  1051. *
  1052. * @param s the string to decode
  1053. * @param options encode options such as URL_SAFE
  1054. * @return the decoded data
  1055. * @throws java.io.IOException if there is an error
  1056. * @throws NullPointerException if <tt>s</tt> is null
  1057. * @since 1.4
  1058. */
  1059. public static byte[] decode( String s, int options ) throws java.io.IOException {
  1060. if( s == null ){
  1061. throw new NullPointerException( "Input string was null." );
  1062. } // end if
  1063. byte[] bytes;
  1064. try {
  1065. bytes = s.getBytes( PREFERRED_ENCODING );
  1066. } // end try
  1067. catch( java.io.UnsupportedEncodingException uee ) {
  1068. bytes = s.getBytes();
  1069. } // end catch
  1070. //</change>
  1071. // Decode
  1072. bytes = decode( bytes, 0, bytes.length, options );
  1073. // Check to see if it's gzip-compressed
  1074. // GZIP Magic Two-Byte Number: 0x8b1f (35615)
  1075. boolean dontGunzip = (options & DONT_GUNZIP) != 0;
  1076. if( (bytes != null) && (bytes.length >= 4) && (!dontGunzip) ) {
  1077. int head = ((int)bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00);
  1078. if( java.util.zip.GZIPInputStream.GZIP_MAGIC == head ) {
  1079. java.io.ByteArrayInputStream bais = null;
  1080. java.util.zip.GZIPInputStream gzis = null;
  1081. java.io.ByteArrayOutputStream baos = null;
  1082. byte[] buffer = new byte[2048];
  1083. int length = 0;
  1084. try {
  1085. baos = new java.io.ByteArrayOutputStream();
  1086. bais = new java.io.ByteArrayInputStream( bytes );
  1087. gzis = new java.util.zip.GZIPInputStream( bais );
  1088. while( ( length = gzis.read( buffer ) ) >= 0 ) {
  1089. baos.write(buffer,0,length);
  1090. } // end while: reading input
  1091. // No error? Get new bytes.
  1092. bytes = baos.toByteArray();
  1093. } // end try
  1094. catch( java.io.IOException e ) {
  1095. e.printStackTrace();
  1096. // Just return originally-decoded bytes
  1097. } // end catch
  1098. finally {
  1099. try{ baos.close(); } catch( Exception e ){}
  1100. try{ gzis.close(); } catch( Exception e ){}
  1101. try{ bais.close(); } catch( Exception e ){}
  1102. } // end finally
  1103. } // end if: gzipped
  1104. } // end if: bytes.length >= 2
  1105. return bytes;
  1106. } // end decode
  1107. /**
  1108. * Attempts to decode Base64 data and deserialize a Java
  1109. * Object within. Returns <tt>null</tt> if there was an error.
  1110. *
  1111. * @param encodedObject The Base64 data to decode
  1112. * @return The decoded and deserialized object
  1113. * @throws NullPointerException if encodedObject is null
  1114. * @throws java.io.IOException if there is a general error
  1115. * @throws ClassNotFoundException if the decoded object is of a
  1116. * class that cannot be found by the JVM
  1117. * @since 1.5
  1118. */
  1119. public static Object decodeToObject( String encodedObject )
  1120. throws java.io.IOException, java.lang.ClassNotFoundException {
  1121. return decodeToObject(encodedObject,NO_OPTIONS,null);
  1122. }
  1123. /**
  1124. * Attempts to decode Base64 data and deserialize a Java
  1125. * Object within. Returns <tt>null</tt> if there was an error.
  1126. * If <tt>loader</tt> is not null, it will be the class loader
  1127. * used when deserializing.
  1128. *
  1129. * @param encodedObject The Base64 data to decode
  1130. * @param options Various parameters related to decoding
  1131. * @param loader Optional class loader to use in deserializing classes.
  1132. * @return The decoded and deserialized object
  1133. * @throws NullPointerException if encodedObject is null
  1134. * @throws java.io.IOException if there is a general error
  1135. * @throws ClassNotFoundException if the decoded object is of a
  1136. * class that cannot be found by the JVM
  1137. * @since 2.3.4
  1138. */
  1139. public static Object decodeToObject(
  1140. String encodedObject, int options, final ClassLoader loader )
  1141. throws java.io.IOException, java.lang.ClassNotFoundException {
  1142. // Decode and gunzip if necessary
  1143. byte[] objBytes = decode( encodedObject, options );
  1144. java.io.ByteArrayInputStream bais = null;
  1145. java.io.ObjectInputStream ois = null;
  1146. Object obj = null;
  1147. try {
  1148. bais = new java.io.ByteArrayInputStream( objBytes );
  1149. // If no custom class loader is provided, use Java's builtin OIS.
  1150. if( loader == null ){
  1151. ois = new java.io.ObjectInputStream( bais );
  1152. } // end if: no loader provided
  1153. // Else make a customized object input stream that uses
  1154. // the provided class loader.
  1155. else {
  1156. ois = new java.io.ObjectInputStream(bais){
  1157. @Override
  1158. public Class<?> resolveClass(java.io.ObjectStreamClass streamClass)
  1159. throws java.io.IOException, ClassNotFoundException {
  1160. Class c = Class.forName(streamClass.getName(), false, loader);
  1161. if( c == null ){
  1162. return super.resolveClass(streamClass);
  1163. } else {
  1164. return c; // Class loader knows of this class.
  1165. } // end else: not null
  1166. } // end resolveClass
  1167. }; // end ois
  1168. } // end else: no custom class loader
  1169. obj = ois.readObject();
  1170. } // end try
  1171. catch( java.io.IOException e ) {
  1172. throw e; // Catch and throw in order to execute finally{}
  1173. } // end catch
  1174. catch( java.lang.ClassNotFoundException e ) {
  1175. throw e; // Catch and throw in order to execute finally{}
  1176. } // end catch
  1177. finally {
  1178. try{ bais.close(); } catch( Exception e ){}
  1179. try{ ois.close(); } catch( Exception e ){}
  1180. } // end finally
  1181. return obj;
  1182. } // end decodeObject
  1183. /**
  1184. * Convenience method for encoding data to a file.
  1185. *
  1186. * <p>As of v 2.3, if there is a error,
  1187. * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
  1188. * In earlier versions, it just returned false, but
  1189. * in retrospect that's a pretty poor way to handle it.</p>
  1190. *
  1191. * @param dataToEncode byte array of data to encode in base64 form
  1192. * @param filename Filename for saving encoded data
  1193. * @throws java.io.IOException if there is an error
  1194. * @throws NullPointerException if dataToEncode is null
  1195. * @since 2.1
  1196. */
  1197. public static void encodeToFile( byte[] dataToEncode, String filename )
  1198. throws java.io.IOException {
  1199. if( dataToEncode == null ){
  1200. throw new NullPointerException( "Data to encode was null." );
  1201. } // end iff
  1202. Base64.OutputStream bos = null;
  1203. try {
  1204. bos = new Base64.OutputStream(
  1205. new java.io.FileOutputStream( filename ), Base64.ENCODE );
  1206. bos.write( dataToEncode );
  1207. } // end try
  1208. catch( java.io.IOException e ) {
  1209. throw e; // Catch and throw to execute finally{} block
  1210. } // end catch: java.io.IOException
  1211. finally {
  1212. try{ bos.close(); } catch( Exception e ){}
  1213. } // end finally
  1214. } // end encodeToFile
  1215. /**
  1216. * Convenience method for decoding data to a file.
  1217. *
  1218. * <p>As of v 2.3, if there is a error,
  1219. * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
  1220. * In earlier versions, it just returned false, but
  1221. * in retrospect that's a pretty poor way to handle it.</p>
  1222. *
  1223. * @param dataToDecode Base64-encoded data as a string
  1224. * @param filename Filename for saving decoded data
  1225. * @throws java.io.IOException if there is an error
  1226. * @since 2.1
  1227. */
  1228. public static void decodeToFile( String dataToDecode, String filename )
  1229. throws java.io.IOException {
  1230. Base64.OutputStream bos = null;
  1231. try{
  1232. bos = new Base64.OutputStream(
  1233. new java.io.FileOutputStream( filename ), Base64.DECODE );
  1234. bos.write( dataToDecode.getBytes( PREFERRED_ENCODING ) );
  1235. } // end try
  1236. catch( java.io.IOException e ) {
  1237. throw e; // Catch and throw to execute finally{} block
  1238. } // end catch: java.io.IOException
  1239. finally {
  1240. try{ bos.close(); } catch( Exception e ){}
  1241. } // end finally
  1242. } // end decodeToFile
  1243. /**
  1244. * Convenience method for reading a base64-encoded
  1245. * file and decoding it.
  1246. *
  1247. * <p>As of v 2.3, if there is a error,
  1248. * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
  1249. * In earlier versions, it just returned false, but
  1250. * in retrospect that's a pretty poor way to handle it.</p>
  1251. *
  1252. * @param filename Filename for reading encoded data
  1253. * @return decoded byte array
  1254. * @throws java.io.IOException if there is an error
  1255. * @since 2.1
  1256. */
  1257. public static byte[] decodeFromFile( String filename )
  1258. throws java.io.IOException {
  1259. byte[] decodedData = null;
  1260. Base64.InputStream bis = null;
  1261. try
  1262. {
  1263. // Set up some useful variables
  1264. java.io.File file = new java.io.File( filename );
  1265. byte[] buffer = null;
  1266. int length = 0;
  1267. int numBytes = 0;
  1268. // Check for size of file
  1269. if( file.length() > Integer.MAX_VALUE )
  1270. {
  1271. throw new java.io.IOException( "File is too big for this convenience method (" + file.length() + " bytes)." );
  1272. } // end if: file too big for int index
  1273. buffer = new byte[ (int)file.length() ];
  1274. // Open a stream
  1275. bis = new Base64.InputStream(
  1276. new java.io.BufferedInputStream(
  1277. new java.io.FileInputStream( file ) ), Base64.DECODE );