Posted By

r_aragao on 07/12/10


Tagged


Versions (?)

Teste


 / Published in: Java
 

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

Report this snippet  

You need to login to post a comment.