/plugins/SVNPlugin/tags/1.6.0/src/ise/plugin/svn/library/Base64.java

# · Java · 1436 lines · 687 code · 245 blank · 504 comment · 92 complexity · fddb26305fe8321f4f8a7debb3baf3be MD5 · raw file

  1. package ise.plugin.svn.library;
  2. /**
  3. * Encodes and decodes to and from Base64 notation.
  4. *
  5. * <p>
  6. * Change Log:
  7. * </p>
  8. * <ul>
  9. * <li>v2.1 - Cleaned up javadoc comments and unused variables and methods. Added
  10. * some convenience methods for reading and writing to and from files.</li>
  11. * <li>v2.0.2 - Now specifies UTF-8 encoding in places where the code fails on systems
  12. * with other encodings (like EBCDIC).</li>
  13. * <li>v2.0.1 - Fixed an error when decoding a single byte, that is, when the
  14. * encoded data was a single byte.</li>
  15. * <li>v2.0 - I got rid of methods that used booleans to set options.
  16. * Now everything is more consolidated and cleaner. The code now detects
  17. * when data that's being decoded is gzip-compressed and will decompress it
  18. * automatically. Generally things are cleaner. You'll probably have to
  19. * change some method calls that you were making to support the new
  20. * options format (<tt>int</tt>s that you "OR" together).</li>
  21. * <li>v1.5.1 - Fixed bug when decompressing and decoding to a
  22. * byte[] using <tt>decode( String s, boolean gzipCompressed )</tt>.
  23. * Added the ability to "suspend" encoding in the Output Stream so
  24. * you can turn on and off the encoding if you need to embed base64
  25. * data in an otherwise "normal" stream (like an XML file).</li>
  26. * <li>v1.5 - Output stream pases on flush() command but doesn't do anything itself.
  27. * This helps when using GZIP streams.
  28. * Added the ability to GZip-compress objects before encoding them.</li>
  29. * <li>v1.4 - Added helper methods to read/write files.</li>
  30. * <li>v1.3.6 - Fixed OutputStream.flush() so that 'position' is reset.</li>
  31. * <li>v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in input stream
  32. * where last buffer being read, if not completely full, was not returned.</li>
  33. * <li>v1.3.4 - Fixed when "improperly padded stream" error was thrown at the wrong time.</li>
  34. * <li>v1.3.3 - Fixed I/O streams which were totally messed up.</li>
  35. * </ul>
  36. *
  37. * <p>
  38. * I am placing this code in the Public Domain. Do with it as you will.
  39. * This software comes with no guarantees or warranties but with
  40. * plenty of well-wishing instead!
  41. * Please visit <a href="http://iharder.net/base64">http://iharder.net/base64</a>
  42. * periodically to check for updates or to contribute improvements.
  43. * </p>
  44. *
  45. * @author Robert Harder
  46. * @author rob@iharder.net
  47. * @version 2.1
  48. */
  49. public class Base64 {
  50. /* ******** P U B L I C F I E L D S ******** */
  51. /** No options specified. Value is zero. */
  52. public final static int NO_OPTIONS = 0;
  53. /** Specify encoding. */
  54. public final static int ENCODE = 1;
  55. /** Specify decoding. */
  56. public final static int DECODE = 0;
  57. /** Specify that data should be gzip-compressed. */
  58. public final static int GZIP = 2;
  59. /** Don't break lines when encoding (violates strict Base64 specification) */
  60. public final static int DONT_BREAK_LINES = 8;
  61. /* ******** P R I V A T E F I E L D S ******** */
  62. /** Maximum line length (76) of Base64 output. */
  63. private final static int MAX_LINE_LENGTH = 76;
  64. /** The equals sign (=) as a byte. */
  65. private final static byte EQUALS_SIGN = ( byte ) '=';
  66. /** The new line character (\n) as a byte. */
  67. private final static byte NEW_LINE = ( byte ) '\n';
  68. /** Preferred encoding. */
  69. private final static String PREFERRED_ENCODING = "UTF-8";
  70. /** The 64 valid Base64 values. */
  71. private final static byte[] ALPHABET;
  72. private final static byte[] _NATIVE_ALPHABET = /* May be something funny like EBCDIC */
  73. {
  74. ( byte ) 'A', ( byte ) 'B', ( byte ) 'C', ( byte ) 'D', ( byte ) 'E', ( byte ) 'F', ( byte ) 'G',
  75. ( byte ) 'H', ( byte ) 'I', ( byte ) 'J', ( byte ) 'K', ( byte ) 'L', ( byte ) 'M', ( byte ) 'N',
  76. ( byte ) 'O', ( byte ) 'P', ( byte ) 'Q', ( byte ) 'R', ( byte ) 'S', ( byte ) 'T', ( byte ) 'U',
  77. ( byte ) 'V', ( byte ) 'W', ( byte ) 'X', ( byte ) 'Y', ( byte ) 'Z',
  78. ( byte ) 'a', ( byte ) 'b', ( byte ) 'c', ( byte ) 'd', ( byte ) 'e', ( byte ) 'f', ( byte ) 'g',
  79. ( byte ) 'h', ( byte ) 'i', ( byte ) 'j', ( byte ) 'k', ( byte ) 'l', ( byte ) 'm', ( byte ) 'n',
  80. ( byte ) 'o', ( byte ) 'p', ( byte ) 'q', ( byte ) 'r', ( byte ) 's', ( byte ) 't', ( byte ) 'u',
  81. ( byte ) 'v', ( byte ) 'w', ( byte ) 'x', ( byte ) 'y', ( byte ) 'z',
  82. ( byte ) '0', ( byte ) '1', ( byte ) '2', ( byte ) '3', ( byte ) '4', ( byte ) '5',
  83. ( byte ) '6', ( byte ) '7', ( byte ) '8', ( byte ) '9', ( byte ) '+', ( byte ) '/'
  84. };
  85. /** Determine which ALPHABET to use. */
  86. static
  87. {
  88. byte[] __bytes;
  89. try {
  90. __bytes = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".getBytes( PREFERRED_ENCODING );
  91. } // end try
  92. catch ( java.io.UnsupportedEncodingException use ) {
  93. __bytes = _NATIVE_ALPHABET; // Fall back to native encoding
  94. } // end catch
  95. ALPHABET = __bytes;
  96. } // end static
  97. /**
  98. * Translates a Base64 value to either its 6-bit reconstruction value
  99. * or a negative number indicating some other meaning.
  100. **/
  101. private final static byte[] DECODABET =
  102. {
  103. -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8
  104. -5, -5, // Whitespace: Tab and Linefeed
  105. -9, -9, // Decimal 11 - 12
  106. -5, // Whitespace: Carriage Return
  107. -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26
  108. -9, -9, -9, -9, -9, // Decimal 27 - 31
  109. -5, // Whitespace: Space
  110. -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42
  111. 62, // Plus sign at decimal 43
  112. -9, -9, -9, // Decimal 44 - 46
  113. 63, // Slash at decimal 47
  114. 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine
  115. -9, -9, -9, // Decimal 58 - 60
  116. -1, // Equals sign at decimal 61
  117. -9, -9, -9, // Decimal 62 - 64
  118. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N'
  119. 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z'
  120. -9, -9, -9, -9, -9, -9, // Decimal 91 - 96
  121. 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm'
  122. 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z'
  123. -9, -9, -9, -9 // Decimal 123 - 126
  124. /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139
  125. -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
  126. -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
  127. -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
  128. -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
  129. -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
  130. -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
  131. -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
  132. -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
  133. -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */
  134. };
  135. // I think I end up not using the BAD_ENCODING indicator.
  136. //private final static byte BAD_ENCODING = -9; // Indicates error in encoding
  137. private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding
  138. private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding
  139. /** Defeats instantiation. */
  140. private Base64() {}
  141. /* ******** E N C O D I N G M E T H O D S ******** */
  142. /**
  143. * Encodes up to the first three bytes of array <var>threeBytes</var>
  144. * and returns a four-byte array in Base64 notation.
  145. * The actual number of significant bytes in your array is
  146. * given by <var>numSigBytes</var>.
  147. * The array <var>threeBytes</var> needs only be as big as
  148. * <var>numSigBytes</var>.
  149. * Code can reuse a byte array by passing a four-byte array as <var>b4</var>.
  150. *
  151. * @param b4 A reusable byte array to reduce array instantiation
  152. * @param threeBytes the array to convert
  153. * @param numSigBytes the number of significant bytes in your array
  154. * @return four byte array in Base64 notation.
  155. * @since 1.5.1
  156. */
  157. private static byte[] encode3to4( byte[] b4, byte[] threeBytes, int numSigBytes ) {
  158. encode3to4( threeBytes, 0, numSigBytes, b4, 0 );
  159. return b4;
  160. } // end encode3to4
  161. /**
  162. * Encodes up to three bytes of the array <var>source</var>
  163. * and writes the resulting four Base64 bytes to <var>destination</var>.
  164. * The source and destination arrays can be manipulated
  165. * anywhere along their length by specifying
  166. * <var>srcOffset</var> and <var>destOffset</var>.
  167. * This method does not check to make sure your arrays
  168. * are large enough to accomodate <var>srcOffset</var> + 3 for
  169. * the <var>source</var> array or <var>destOffset</var> + 4 for
  170. * the <var>destination</var> array.
  171. * The actual number of significant bytes in your array is
  172. * given by <var>numSigBytes</var>.
  173. *
  174. * @param source the array to convert
  175. * @param srcOffset the index where conversion begins
  176. * @param numSigBytes the number of significant bytes in your array
  177. * @param destination the array to hold the conversion
  178. * @param destOffset the index where output will be put
  179. * @return the <var>destination</var> array
  180. * @since 1.3
  181. */
  182. private static byte[] encode3to4(
  183. byte[] source, int srcOffset, int numSigBytes,
  184. byte[] destination, int destOffset ) {
  185. // 1 2 3
  186. // 01234567890123456789012345678901 Bit position
  187. // --------000000001111111122222222 Array position from threeBytes
  188. // --------| || || || | Six bit groups to index ALPHABET
  189. // >>18 >>12 >> 6 >> 0 Right shift necessary
  190. // 0x3f 0x3f 0x3f Additional AND
  191. // Create buffer with zero-padding if there are only one or two
  192. // significant bytes passed in the array.
  193. // We have to shift left 24 in order to flush out the 1's that appear
  194. // when Java treats a value as negative that is cast from a byte to an int.
  195. int inBuff = ( numSigBytes > 0 ? ( ( source[ srcOffset ] << 24 ) >>> 8 ) : 0 )
  196. | ( numSigBytes > 1 ? ( ( source[ srcOffset + 1 ] << 24 ) >>> 16 ) : 0 )
  197. | ( numSigBytes > 2 ? ( ( source[ srcOffset + 2 ] << 24 ) >>> 24 ) : 0 );
  198. switch ( numSigBytes ) {
  199. case 3:
  200. destination[ destOffset ] = ALPHABET[ ( inBuff >>> 18 ) ];
  201. destination[ destOffset + 1 ] = ALPHABET[ ( inBuff >>> 12 ) & 0x3f ];
  202. destination[ destOffset + 2 ] = ALPHABET[ ( inBuff >>> 6 ) & 0x3f ];
  203. destination[ destOffset + 3 ] = ALPHABET[ ( inBuff ) & 0x3f ];
  204. return destination;
  205. case 2:
  206. destination[ destOffset ] = ALPHABET[ ( inBuff >>> 18 ) ];
  207. destination[ destOffset + 1 ] = ALPHABET[ ( inBuff >>> 12 ) & 0x3f ];
  208. destination[ destOffset + 2 ] = ALPHABET[ ( inBuff >>> 6 ) & 0x3f ];
  209. destination[ destOffset + 3 ] = EQUALS_SIGN;
  210. return destination;
  211. case 1:
  212. destination[ destOffset ] = ALPHABET[ ( inBuff >>> 18 ) ];
  213. destination[ destOffset + 1 ] = ALPHABET[ ( inBuff >>> 12 ) & 0x3f ];
  214. destination[ destOffset + 2 ] = EQUALS_SIGN;
  215. destination[ destOffset + 3 ] = EQUALS_SIGN;
  216. return destination;
  217. default:
  218. return destination;
  219. } // end switch
  220. } // end encode3to4
  221. /**
  222. * Serializes an object and returns the Base64-encoded
  223. * version of that serialized object. If the object
  224. * cannot be serialized or there is another error,
  225. * the method will return <tt>null</tt>.
  226. * The object is not GZip-compressed before being encoded.
  227. *
  228. * @param serializableObject The object to encode
  229. * @return The Base64-encoded object
  230. * @since 1.4
  231. */
  232. public static String encodeObject( java.io.Serializable serializableObject ) {
  233. return encodeObject( serializableObject, NO_OPTIONS );
  234. } // end encodeObject
  235. /**
  236. * Serializes an object and returns the Base64-encoded
  237. * version of that serialized object. If the object
  238. * cannot be serialized or there is another error,
  239. * the method will return <tt>null</tt>.
  240. * <p>
  241. * Valid options:<pre>
  242. * GZIP: gzip-compresses object before encoding it.
  243. * DONT_BREAK_LINES: don't break lines at 76 characters
  244. * <i>Note: Technically, this makes your encoding non-compliant.</i>
  245. * </pre>
  246. * <p>
  247. * Example: <code>encodeObject( myObj, Base64.GZIP )</code> or
  248. * <p>
  249. * Example: <code>encodeObject( myObj, Base64.GZIP | Base64.DONT_BREAK_LINES )</code>
  250. *
  251. * @param serializableObject The object to encode
  252. * @param options Specified options
  253. * @return The Base64-encoded object
  254. * @see Base64#GZIP
  255. * @see Base64#DONT_BREAK_LINES
  256. * @since 2.0
  257. */
  258. public static String encodeObject( java.io.Serializable serializableObject, int options ) {
  259. // Streams
  260. java.io.ByteArrayOutputStream baos = null;
  261. java.io.OutputStream b64os = null;
  262. java.io.ObjectOutputStream oos = null;
  263. java.util.zip.GZIPOutputStream gzos = null;
  264. // Isolate options
  265. int gzip = ( options & GZIP );
  266. int dontBreakLines = ( options & DONT_BREAK_LINES );
  267. try {
  268. // ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream
  269. baos = new java.io.ByteArrayOutputStream();
  270. b64os = new Base64.OutputStream( baos, ENCODE | dontBreakLines );
  271. // GZip?
  272. if ( gzip == GZIP ) {
  273. gzos = new java.util.zip.GZIPOutputStream( b64os );
  274. oos = new java.io.ObjectOutputStream( gzos );
  275. } // end if: gzip
  276. else
  277. oos = new java.io.ObjectOutputStream( b64os );
  278. oos.writeObject( serializableObject );
  279. } // end try
  280. catch ( java.io.IOException e ) {
  281. e.printStackTrace();
  282. return null;
  283. } // end catch
  284. finally {
  285. try {
  286. oos.close();
  287. }
  288. catch ( Exception e ) {}
  289. try {
  290. gzos.close();
  291. }
  292. catch ( Exception e ) {}
  293. try {
  294. b64os.close();
  295. }
  296. catch ( Exception e ) {}
  297. try {
  298. baos.close();
  299. }
  300. catch ( Exception e ) {}
  301. } // end finally
  302. // Return value according to relevant encoding.
  303. try {
  304. return new String( baos.toByteArray(), PREFERRED_ENCODING );
  305. } // end try
  306. catch ( java.io.UnsupportedEncodingException uue ) {
  307. return new String( baos.toByteArray() );
  308. } // end catch
  309. } // end encode
  310. /**
  311. * Encodes a byte array into Base64 notation.
  312. * Does not GZip-compress data.
  313. *
  314. * @param source The data to convert
  315. * @since 1.4
  316. */
  317. public static String encodeBytes( byte[] source ) {
  318. return encodeBytes( source, 0, source.length, NO_OPTIONS );
  319. } // end encodeBytes
  320. /**
  321. * Encodes a byte array into Base64 notation.
  322. * <p>
  323. * Valid options:<pre>
  324. * GZIP: gzip-compresses object before encoding it.
  325. * DONT_BREAK_LINES: don't break lines at 76 characters
  326. * <i>Note: Technically, this makes your encoding non-compliant.</i>
  327. * </pre>
  328. * <p>
  329. * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
  330. * <p>
  331. * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code>
  332. *
  333. *
  334. * @param source The data to convert
  335. * @param options Specified options
  336. * @see Base64#GZIP
  337. * @see Base64#DONT_BREAK_LINES
  338. * @since 2.0
  339. */
  340. public static String encodeBytes( byte[] source, int options ) {
  341. return encodeBytes( source, 0, source.length, options );
  342. } // end encodeBytes
  343. /**
  344. * Encodes a byte array into Base64 notation.
  345. * Does not GZip-compress data.
  346. *
  347. * @param source The data to convert
  348. * @param off Offset in array where conversion should begin
  349. * @param len Length of data to convert
  350. * @since 1.4
  351. */
  352. public static String encodeBytes( byte[] source, int off, int len ) {
  353. return encodeBytes( source, off, len, NO_OPTIONS );
  354. } // end encodeBytes
  355. /**
  356. * Encodes a byte array into Base64 notation.
  357. * <p>
  358. * Valid options:<pre>
  359. * GZIP: gzip-compresses object before encoding it.
  360. * DONT_BREAK_LINES: don't break lines at 76 characters
  361. * <i>Note: Technically, this makes your encoding non-compliant.</i>
  362. * </pre>
  363. * <p>
  364. * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
  365. * <p>
  366. * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code>
  367. *
  368. *
  369. * @param source The data to convert
  370. * @param off Offset in array where conversion should begin
  371. * @param len Length of data to convert
  372. * @param options Specified options
  373. * @see Base64#GZIP
  374. * @see Base64#DONT_BREAK_LINES
  375. * @since 2.0
  376. */
  377. public static String encodeBytes( byte[] source, int off, int len, int options ) {
  378. // Isolate options
  379. int dontBreakLines = ( options & DONT_BREAK_LINES );
  380. int gzip = ( options & GZIP );
  381. // Compress?
  382. if ( gzip == GZIP ) {
  383. java.io.ByteArrayOutputStream baos = null;
  384. java.util.zip.GZIPOutputStream gzos = null;
  385. Base64.OutputStream b64os = null;
  386. try {
  387. // GZip -> Base64 -> ByteArray
  388. baos = new java.io.ByteArrayOutputStream();
  389. b64os = new Base64.OutputStream( baos, ENCODE | dontBreakLines );
  390. gzos = new java.util.zip.GZIPOutputStream( b64os );
  391. gzos.write( source, off, len );
  392. gzos.close();
  393. } // end try
  394. catch ( java.io.IOException e ) {
  395. e.printStackTrace();
  396. return null;
  397. } // end catch
  398. finally {
  399. try {
  400. gzos.close();
  401. }
  402. catch ( Exception e ) {}
  403. try {
  404. b64os.close();
  405. }
  406. catch ( Exception e ) {}
  407. try {
  408. baos.close();
  409. }
  410. catch ( Exception e ) {}
  411. } // end finally
  412. // Return value according to relevant encoding.
  413. try {
  414. return new String( baos.toByteArray(), PREFERRED_ENCODING );
  415. } // end try
  416. catch ( java.io.UnsupportedEncodingException uue ) {
  417. return new String( baos.toByteArray() );
  418. } // end catch
  419. } // end if: compress
  420. // Else, don't compress. Better not to use streams at all then.
  421. else {
  422. // Convert option to boolean in way that code likes it.
  423. boolean breakLines = dontBreakLines == 0;
  424. int len43 = len * 4 / 3;
  425. byte[] outBuff = new byte[ ( len43 ) // Main 4:3
  426. + ( ( len % 3 ) > 0 ? 4 : 0 ) // Account for padding
  427. + ( breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0 ) ]; // New lines
  428. int d = 0;
  429. int e = 0;
  430. int len2 = len - 2;
  431. int lineLength = 0;
  432. for ( ; d < len2; d += 3, e += 4 ) {
  433. encode3to4( source, d + off, 3, outBuff, e );
  434. lineLength += 4;
  435. if ( breakLines && lineLength == MAX_LINE_LENGTH ) {
  436. outBuff[ e + 4 ] = NEW_LINE;
  437. e++;
  438. lineLength = 0;
  439. } // end if: end of line
  440. } // en dfor: each piece of array
  441. if ( d < len ) {
  442. encode3to4( source, d + off, len - d, outBuff, e );
  443. e += 4;
  444. } // end if: some padding needed
  445. // Return value according to relevant encoding.
  446. try {
  447. return new String( outBuff, 0, e, PREFERRED_ENCODING );
  448. } // end try
  449. catch ( java.io.UnsupportedEncodingException uue ) {
  450. return new String( outBuff, 0, e );
  451. } // end catch
  452. } // end else: don't compress
  453. } // end encodeBytes
  454. /* ******** D E C O D I N G M E T H O D S ******** */
  455. /**
  456. * Decodes four bytes from array <var>source</var>
  457. * and writes the resulting bytes (up to three of them)
  458. * to <var>destination</var>.
  459. * The source and destination arrays can be manipulated
  460. * anywhere along their length by specifying
  461. * <var>srcOffset</var> and <var>destOffset</var>.
  462. * This method does not check to make sure your arrays
  463. * are large enough to accomodate <var>srcOffset</var> + 4 for
  464. * the <var>source</var> array or <var>destOffset</var> + 3 for
  465. * the <var>destination</var> array.
  466. * This method returns the actual number of bytes that
  467. * were converted from the Base64 encoding.
  468. *
  469. *
  470. * @param source the array to convert
  471. * @param srcOffset the index where conversion begins
  472. * @param destination the array to hold the conversion
  473. * @param destOffset the index where output will be put
  474. * @return the number of decoded bytes converted
  475. * @since 1.3
  476. */
  477. private static int decode4to3( byte[] source, int srcOffset, byte[] destination, int destOffset ) {
  478. // Example: Dk==
  479. if ( source[ srcOffset + 2 ] == EQUALS_SIGN ) {
  480. // Two ways to do the same thing. Don't know which way I like best.
  481. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
  482. // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 );
  483. int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
  484. | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 );
  485. destination[ destOffset ] = ( byte ) ( outBuff >>> 16 );
  486. return 1;
  487. }
  488. // Example: DkL=
  489. else if ( source[ srcOffset + 3 ] == EQUALS_SIGN ) {
  490. // Two ways to do the same thing. Don't know which way I like best.
  491. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
  492. // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
  493. // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 );
  494. int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
  495. | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
  496. | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 );
  497. destination[ destOffset ] = ( byte ) ( outBuff >>> 16 );
  498. destination[ destOffset + 1 ] = ( byte ) ( outBuff >>> 8 );
  499. return 2;
  500. }
  501. // Example: DkLE
  502. else {
  503. try {
  504. // Two ways to do the same thing. Don't know which way I like best.
  505. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
  506. // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
  507. // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 )
  508. // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 );
  509. int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
  510. | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
  511. | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 )
  512. | ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) );
  513. destination[ destOffset ] = ( byte ) ( outBuff >> 16 );
  514. destination[ destOffset + 1 ] = ( byte ) ( outBuff >> 8 );
  515. destination[ destOffset + 2 ] = ( byte ) ( outBuff );
  516. return 3;
  517. }
  518. catch ( Exception e ) {
  519. System.out.println( "" + source[ srcOffset ] + ": " + ( DECODABET[ source[ srcOffset ] ] ) );
  520. System.out.println( "" + source[ srcOffset + 1 ] + ": " + ( DECODABET[ source[ srcOffset + 1 ] ] ) );
  521. System.out.println( "" + source[ srcOffset + 2 ] + ": " + ( DECODABET[ source[ srcOffset + 2 ] ] ) );
  522. System.out.println( "" + source[ srcOffset + 3 ] + ": " + ( DECODABET[ source[ srcOffset + 3 ] ] ) );
  523. return -1;
  524. } //e nd catch
  525. }
  526. } // end decodeToBytes
  527. /**
  528. * Very low-level access to decoding ASCII characters in
  529. * the form of a byte array. Does not support automatically
  530. * gunzipping or any other "fancy" features.
  531. *
  532. * @param source The Base64 encoded data
  533. * @param off The offset of where to begin decoding
  534. * @param len The length of characters to decode
  535. * @return decoded data
  536. * @since 1.3
  537. */
  538. public static byte[] decode( byte[] source, int off, int len ) {
  539. int len34 = len * 3 / 4;
  540. byte[] outBuff = new byte[ len34 ]; // Upper limit on size of output
  541. int outBuffPosn = 0;
  542. byte[] b4 = new byte[ 4 ];
  543. int b4Posn = 0;
  544. int i = 0;
  545. byte sbiCrop = 0;
  546. byte sbiDecode = 0;
  547. for ( i = off; i < off + len; i++ ) {
  548. sbiCrop = ( byte ) ( source[ i ] & 0x7f ); // Only the low seven bits
  549. sbiDecode = DECODABET[ sbiCrop ];
  550. if ( sbiDecode >= WHITE_SPACE_ENC ) // White space, Equals sign or better
  551. {
  552. if ( sbiDecode >= EQUALS_SIGN_ENC ) {
  553. b4[ b4Posn++ ] = sbiCrop;
  554. if ( b4Posn > 3 ) {
  555. outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn );
  556. b4Posn = 0;
  557. // If that was the equals sign, break out of 'for' loop
  558. if ( sbiCrop == EQUALS_SIGN )
  559. break;
  560. } // end if: quartet built
  561. } // end if: equals sign or better
  562. } // end if: white space, equals sign or better
  563. else {
  564. System.err.println( "Bad Base64 input character at " + i + ": " + source[ i ] + "(decimal)" );
  565. return null;
  566. } // end else:
  567. } // each input character
  568. byte[] out = new byte[ outBuffPosn ];
  569. System.arraycopy( outBuff, 0, out, 0, outBuffPosn );
  570. return out;
  571. } // end decode
  572. /**
  573. * Decodes data from Base64 notation, automatically
  574. * detecting gzip-compressed data and decompressing it.
  575. *
  576. * @param s the string to decode
  577. * @return the decoded data
  578. * @since 1.4
  579. */
  580. public static byte[] decode( String s ) {
  581. byte[] bytes;
  582. try {
  583. bytes = s.getBytes( PREFERRED_ENCODING );
  584. } // end try
  585. catch ( java.io.UnsupportedEncodingException uee ) {
  586. bytes = s.getBytes();
  587. } // end catch
  588. //</change>
  589. // Decode
  590. bytes = decode( bytes, 0, bytes.length );
  591. // Check to see if it's gzip-compressed
  592. // GZIP Magic Two-Byte Number: 0x8b1f (35615)
  593. if ( bytes != null && bytes.length >= 4 ) {
  594. int head = ( ( int ) bytes[ 0 ] & 0xff ) | ( ( bytes[ 1 ] << 8 ) & 0xff00 );
  595. if ( java.util.zip.GZIPInputStream.GZIP_MAGIC == head ) {
  596. java.io.ByteArrayInputStream bais = null;
  597. java.util.zip.GZIPInputStream gzis = null;
  598. java.io.ByteArrayOutputStream baos = null;
  599. byte[] buffer = new byte[ 2048 ];
  600. int length = 0;
  601. try {
  602. baos = new java.io.ByteArrayOutputStream();
  603. bais = new java.io.ByteArrayInputStream( bytes );
  604. gzis = new java.util.zip.GZIPInputStream( bais );
  605. while ( ( length = gzis.read( buffer ) ) >= 0 ) {
  606. baos.write( buffer, 0, length );
  607. } // end while: reading input
  608. // No error? Get new bytes.
  609. bytes = baos.toByteArray();
  610. } // end try
  611. catch ( java.io.IOException e ) {
  612. // Just return originally-decoded bytes
  613. } // end catch
  614. finally {
  615. try {
  616. baos.close();
  617. }
  618. catch ( Exception e ) {}
  619. try {
  620. gzis.close();
  621. }
  622. catch ( Exception e ) {}
  623. try {
  624. bais.close();
  625. }
  626. catch ( Exception e ) {}
  627. } // end finally
  628. } // end if: gzipped
  629. } // end if: bytes.length >= 2
  630. return bytes;
  631. } // end decode
  632. /**
  633. * Attempts to decode Base64 data and deserialize a Java
  634. * Object within. Returns <tt>null</tt> if there was an error.
  635. *
  636. * @param encodedObject The Base64 data to decode
  637. * @return The decoded and deserialized object
  638. * @since 1.5
  639. */
  640. public static Object decodeToObject( String encodedObject ) {
  641. // Decode and gunzip if necessary
  642. byte[] objBytes = decode( encodedObject );
  643. java.io.ByteArrayInputStream bais = null;
  644. java.io.ObjectInputStream ois = null;
  645. Object obj = null;
  646. try {
  647. bais = new java.io.ByteArrayInputStream( objBytes );
  648. ois = new java.io.ObjectInputStream( bais );
  649. obj = ois.readObject();
  650. } // end try
  651. catch ( java.io.IOException e ) {
  652. e.printStackTrace();
  653. obj = null;
  654. } // end catch
  655. catch ( java.lang.ClassNotFoundException e ) {
  656. e.printStackTrace();
  657. obj = null;
  658. } // end catch
  659. finally {
  660. try {
  661. bais.close();
  662. }
  663. catch ( Exception e ) {}
  664. try {
  665. ois.close();
  666. }
  667. catch ( Exception e ) {}
  668. } // end finally
  669. return obj;
  670. } // end decodeObject
  671. /**
  672. * Convenience method for encoding data to a file.
  673. *
  674. * @param dataToEncode byte array of data to encode in base64 form
  675. * @param filename Filename for saving encoded data
  676. * @return <tt>true</tt> if successful, <tt>false</tt> otherwise
  677. *
  678. * @since 2.1
  679. */
  680. public static boolean encodeToFile( byte[] dataToEncode, String filename ) {
  681. boolean success = false;
  682. Base64.OutputStream bos = null;
  683. try {
  684. bos = new Base64.OutputStream(
  685. new java.io.FileOutputStream( filename ), Base64.ENCODE );
  686. bos.write( dataToEncode );
  687. success = true;
  688. } // end try
  689. catch ( java.io.IOException e ) {
  690. success = false;
  691. } // end catch: IOException
  692. finally {
  693. try {
  694. bos.close();
  695. }
  696. catch ( Exception e ) {}
  697. } // end finally
  698. return success;
  699. } // end encodeToFile
  700. /**
  701. * Convenience method for decoding data to a file.
  702. *
  703. * @param dataToDecode Base64-encoded data as a string
  704. * @param filename Filename for saving decoded data
  705. * @return <tt>true</tt> if successful, <tt>false</tt> otherwise
  706. *
  707. * @since 2.1
  708. */
  709. public static boolean decodeToFile( String dataToDecode, String filename ) {
  710. boolean success = false;
  711. Base64.OutputStream bos = null;
  712. try {
  713. bos = new Base64.OutputStream(
  714. new java.io.FileOutputStream( filename ), Base64.DECODE );
  715. bos.write( dataToDecode.getBytes( PREFERRED_ENCODING ) );
  716. success = true;
  717. } // end try
  718. catch ( java.io.IOException e ) {
  719. success = false;
  720. } // end catch: IOException
  721. finally {
  722. try {
  723. bos.close();
  724. }
  725. catch ( Exception e ) {}
  726. } // end finally
  727. return success;
  728. } // end decodeToFile
  729. /**
  730. * Convenience method for reading a base64-encoded
  731. * file and decoding it.
  732. *
  733. * @param filename Filename for reading encoded data
  734. * @return decoded byte array or null if unsuccessful
  735. *
  736. * @since 2.1
  737. */
  738. public static byte[] decodeFromFile( String filename ) {
  739. byte[] decodedData = null;
  740. Base64.InputStream bis = null;
  741. try {
  742. // Set up some useful variables
  743. java.io.File file = new java.io.File( filename );
  744. byte[] buffer = null;
  745. int length = 0;
  746. int numBytes = 0;
  747. // Check for size of file
  748. if ( file.length() > Integer.MAX_VALUE ) {
  749. System.err.println( "File is too big for this convenience method (" + file.length() + " bytes)." );
  750. return null;
  751. } // end if: file too big for int index
  752. buffer = new byte[ ( int ) file.length() ];
  753. // Open a stream
  754. bis = new Base64.InputStream(
  755. new java.io.BufferedInputStream(
  756. new java.io.FileInputStream( file ) ), Base64.DECODE );
  757. // Read until done
  758. while ( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 )
  759. length += numBytes;
  760. // Save in a variable to return
  761. decodedData = new byte[ length ];
  762. System.arraycopy( buffer, 0, decodedData, 0, length );
  763. } // end try
  764. catch ( java.io.IOException e ) {
  765. System.err.println( "Error decoding from file " + filename );
  766. } // end catch: IOException
  767. finally {
  768. try {
  769. if ( bis != null ) {
  770. bis.close();
  771. }
  772. }
  773. catch ( Exception e ) {
  774. System.err.println( "Error closing stream." );
  775. }
  776. } // end finally
  777. return decodedData;
  778. } // end decodeFromFile
  779. /**
  780. * Convenience method for reading a binary file
  781. * and base64-encoding it.
  782. *
  783. * @param filename Filename for reading binary data
  784. * @return base64-encoded string or null if unsuccessful
  785. *
  786. * @since 2.1
  787. */
  788. public static String encodeFromFile( String filename ) {
  789. String encodedData = null;
  790. Base64.InputStream bis = null;
  791. try {
  792. // Set up some useful variables
  793. java.io.File file = new java.io.File( filename );
  794. byte[] buffer = new byte[ ( int ) ( file.length() * 1.4 ) ];
  795. int length = 0;
  796. int numBytes = 0;
  797. // Open a stream
  798. bis = new Base64.InputStream(
  799. new java.io.BufferedInputStream(
  800. new java.io.FileInputStream( file ) ), Base64.ENCODE );
  801. // Read until done
  802. while ( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 )
  803. length += numBytes;
  804. // Save in a variable to return
  805. encodedData = new String( buffer, 0, length, Base64.PREFERRED_ENCODING );
  806. } // end try
  807. catch ( java.io.IOException e ) {
  808. System.err.println( "Error encoding from file " + filename );
  809. } // end catch: IOException
  810. finally {
  811. try {
  812. bis.close();
  813. }
  814. catch ( Exception e ) {}
  815. } // end finally
  816. return encodedData;
  817. } // end encodeFromFile
  818. /* ******** I N N E R C L A S S I N P U T S T R E A M ******** */
  819. /**
  820. * A {@link Base64.InputStream} will read data from another
  821. * <tt>java.io.InputStream</tt>, given in the constructor,
  822. * and encode/decode to/from Base64 notation on the fly.
  823. *
  824. * @see Base64
  825. * @since 1.3
  826. */
  827. public static class InputStream extends java.io.FilterInputStream {
  828. private boolean encode; // Encoding or decoding
  829. private int position; // Current position in the buffer
  830. private byte[] buffer; // Small buffer holding converted data
  831. private int bufferLength; // Length of buffer (3 or 4)
  832. private int numSigBytes; // Number of meaningful bytes in the buffer
  833. private int lineLength;
  834. private boolean breakLines; // Break lines at less than 80 characters
  835. /**
  836. * Constructs a {@link Base64.InputStream} in DECODE mode.
  837. *
  838. * @param in the <tt>java.io.InputStream</tt> from which to read data.
  839. * @since 1.3
  840. */
  841. public InputStream( java.io.InputStream in ) {
  842. this( in, DECODE );
  843. } // end constructor
  844. /**
  845. * Constructs a {@link Base64.InputStream} in
  846. * either ENCODE or DECODE mode.
  847. * <p>
  848. * Valid options:<pre>
  849. * ENCODE or DECODE: Encode or Decode as data is read.
  850. * DONT_BREAK_LINES: don't break lines at 76 characters
  851. * (only meaningful when encoding)
  852. * <i>Note: Technically, this makes your encoding non-compliant.</i>
  853. * </pre>
  854. * <p>
  855. * Example: <code>new Base64.InputStream( in, Base64.DECODE )</code>
  856. *
  857. *
  858. * @param in the <tt>java.io.InputStream</tt> from which to read data.
  859. * @param options Specified options
  860. * @see Base64#ENCODE
  861. * @see Base64#DECODE
  862. * @see Base64#DONT_BREAK_LINES
  863. * @since 2.0
  864. */
  865. public InputStream( java.io.InputStream in, int options ) {
  866. super( in );
  867. this.breakLines = ( options & DONT_BREAK_LINES ) != DONT_BREAK_LINES;
  868. this.encode = ( options & ENCODE ) == ENCODE;
  869. this.bufferLength = encode ? 4 : 3;
  870. this.buffer = new byte[ bufferLength ];
  871. this.position = -1;
  872. this.lineLength = 0;
  873. } // end constructor
  874. /**
  875. * Reads enough of the input stream to convert
  876. * to/from Base64 and returns the next byte.
  877. *
  878. * @return next byte
  879. * @since 1.3
  880. */
  881. public int read() throws java.io.IOException {
  882. // Do we need to get data?
  883. if ( position < 0 ) {
  884. if ( encode ) {
  885. byte[] b3 = new byte[ 3 ];
  886. int numBinaryBytes = 0;
  887. for ( int i = 0; i < 3; i++ ) {
  888. try {
  889. int b = in.read();
  890. // If end of stream, b is -1.
  891. if ( b >= 0 ) {
  892. b3[ i ] = ( byte ) b;
  893. numBinaryBytes++;
  894. } // end if: not end of stream
  895. } // end try: read
  896. catch ( java.io.IOException e ) {
  897. // Only a problem if we got no data at all.
  898. if ( i == 0 )
  899. throw e;
  900. } // end catch
  901. } // end for: each needed input byte
  902. if ( numBinaryBytes > 0 ) {
  903. encode3to4( b3, 0, numBinaryBytes, buffer, 0 );
  904. position = 0;
  905. numSigBytes = 4;
  906. } // end if: got data
  907. else {
  908. return -1;
  909. } // end else
  910. } // end if: encoding
  911. // Else decoding
  912. else {
  913. byte[] b4 = new byte[ 4 ];
  914. int i = 0;
  915. for ( i = 0; i < 4; i++ ) {
  916. // Read four "meaningful" bytes:
  917. int b = 0;
  918. do {
  919. b = in.read();
  920. }
  921. while ( b >= 0 && DECODABET[ b & 0x7f ] <= WHITE_SPACE_ENC );
  922. if ( b < 0 )
  923. break; // Reads a -1 if end of stream
  924. b4[ i ] = ( byte ) b;
  925. } // end for: each needed input byte
  926. if ( i == 4 ) {
  927. numSigBytes = decode4to3( b4, 0, buffer, 0 );
  928. position = 0;
  929. } // end if: got four characters
  930. else if ( i == 0 ) {
  931. return -1;
  932. } // end else if: also padded correctly
  933. else {
  934. // Must have broken out from above.
  935. throw new java.io.IOException( "Improperly padded Base64 input." );
  936. } // end
  937. } // end else: decode
  938. } // end else: get data
  939. // Got data?
  940. if ( position >= 0 ) {
  941. // End of relevant data?
  942. if ( /*!encode &&*/ position >= numSigBytes )
  943. return -1;
  944. if ( encode && breakLines && lineLength >= MAX_LINE_LENGTH ) {
  945. lineLength = 0;
  946. return '\n';
  947. } // end if
  948. else {
  949. lineLength++; // This isn't important when decoding
  950. // but throwing an extra "if" seems
  951. // just as wasteful.
  952. int b = buffer[ position++ ];
  953. if ( position >= bufferLength )
  954. position = -1;
  955. return b & 0xFF; // This is how you "cast" a byte that's
  956. // intended to be unsigned.
  957. } // end else
  958. } // end if: position >= 0
  959. // Else error
  960. else {
  961. // When JDK1.4 is more accepted, use an assertion here.
  962. throw new java.io.IOException( "Error in Base64 code reading stream." );
  963. } // end else
  964. } // end read
  965. /**
  966. * Calls {@link #read()} repeatedly until the end of stream
  967. * is reached or <var>len</var> bytes are read.
  968. * Returns number of bytes read into array or -1 if
  969. * end of stream is encountered.
  970. *
  971. * @param dest array to hold values
  972. * @param off offset for array
  973. * @param len max number of bytes to read into array
  974. * @return bytes read into array or -1 if end of stream is encountered.
  975. * @since 1.3
  976. */
  977. public int read( byte[] dest, int off, int len ) throws java.io.IOException {
  978. int i;
  979. int b;
  980. for ( i = 0; i < len; i++ ) {
  981. b = read();
  982. //if( b < 0 && i == 0 )
  983. // return -1;
  984. if ( b >= 0 )
  985. dest[ off + i ] = ( byte ) b;
  986. else if ( i == 0 )
  987. return -1;
  988. else
  989. break; // Out of 'for' loop
  990. } // end for: each byte read
  991. return i;
  992. } // end read
  993. } // end inner class InputStream
  994. /* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */
  995. /**
  996. * A {@link Base64.OutputStream} will write data to another
  997. * <tt>java.io.OutputStream</tt>, given in the constructor,
  998. * and encode/decode to/from Base64 notation on the fly.
  999. *
  1000. * @see Base64
  1001. * @since 1.3
  1002. */
  1003. public static class OutputStream extends java.io.FilterOutputStream {
  1004. private boolean encode;
  1005. private int position;
  1006. private byte[] buffer;
  1007. private int bufferLength;
  1008. private int lineLength;
  1009. private boolean breakLines;
  1010. private byte[] b4; // Scratch used in a few places
  1011. private boolean suspendEncoding;
  1012. /**
  1013. * Constructs a {@link Base64.OutputStream} in ENCODE mode.
  1014. *
  1015. * @param out the <tt>java.io.OutputStream</tt> to which data will be written.
  1016. * @since 1.3
  1017. */
  1018. public OutputStream( java.io.OutputStream out ) {
  1019. this( out, ENCODE );
  1020. } // end constructor
  1021. /**
  1022. * Constructs a {@link Base64.OutputStream} in
  1023. * either ENCODE or DECODE mode.
  1024. * <p>
  1025. * Valid options:<pre>
  1026. * ENCODE or DECODE: Encode or Decode as data is read.
  1027. * DONT_BREAK_LINES: don't break lines at 76 characters
  1028. * (only meaningful when encoding)
  1029. * <i>Note: Technically, this makes your encoding non-compliant.</i>
  1030. * </pre>
  1031. * <p>
  1032. * Example: <code>new Base64.OutputStream( out, Base64.ENCODE )</code>
  1033. *
  1034. * @param out the <tt>java.io.OutputStream</tt> to which data will be written.
  1035. * @param options Specified options.
  1036. * @see Base64#ENCODE
  1037. * @see Base64#DECODE
  1038. * @see Base64#DONT_BREAK_LINES
  1039. * @since 1.3
  1040. */
  1041. public OutputStream( java.io.OutputStream out, int options ) {
  1042. super( out );
  1043. this.breakLines = ( options & DONT_BREAK_LINES ) != DONT_BREAK_LINES;
  1044. this.encode = ( options & ENCODE ) == ENCODE;
  1045. this.bufferLength = encode ? 3 : 4;
  1046. this.buffer = new byte[ bufferLength ];
  1047. this.position = 0;
  1048. this.lineLength = 0;
  1049. this.suspendEncoding = false;
  1050. this.b4 = new byte[ 4 ];
  1051. } // end constructor
  1052. /**
  1053. * Writes the byte to the output stream after
  1054. * converting to/from Base64 notation.
  1055. * When encoding, bytes are buffered three
  1056. * at a time before the output stream actually
  1057. * gets a write() call.
  1058. * When decoding, bytes are buffered four
  1059. * at a time.
  1060. *
  1061. * @param theByte the byte to write
  1062. * @since 1.3
  1063. */
  1064. public void write( int theByte ) throws java.io.IOException {
  1065. // Encoding suspended?
  1066. if ( suspendEncoding ) {
  1067. super.out.write( theByte );
  1068. return ;
  1069. } // end if: supsended
  1070. // Encode?
  1071. if ( encode ) {
  1072. buffer[ position++ ] = ( byte ) theByte;
  1073. if ( position >= bufferLength ) // Enough to encode.
  1074. {
  1075. out.write( encode3to4( b4, buffer, bufferLength ) );
  1076. lineLength += 4;
  1077. if ( breakLines && lineLength >= MAX_LINE_LENGTH ) {
  1078. out.write( NEW_LINE );
  1079. lineLength = 0;
  1080. } // end if: end of line
  1081. position = 0;
  1082. } // end if: enough to output
  1083. } // end if: encoding
  1084. // Else, Decoding
  1085. else {
  1086. // Meaningful Base64 character?
  1087. if ( DECODABET[ theByte & 0x7f ] > WHITE_SPACE_ENC ) {
  1088. buffer[ position++ ] = ( byte ) theByte;
  1089. if ( position >= bufferLength ) // Enough to output.
  1090. {
  1091. int len = Base64.decode4to3( buffer, 0, b4, 0 );
  1092. out.write( b4, 0, len );
  1093. //out.write( Base64.decode4to3( buffer ) );
  1094. position = 0;
  1095. } // end if: enough to output
  1096. } // end if: meaningful base64 character
  1097. else if ( DECODABET[ theByte & 0x7f ] != WHITE_SPACE_ENC ) {
  1098. throw new java.io.IOException( "Invalid character in Base64 data." );
  1099. } // end else: not white space either
  1100. } // end else: decoding
  1101. } // end write
  1102. /**
  1103. * Calls {@link #write(int)} repeatedly until <var>len</var>
  1104. * bytes are written.
  1105. *
  1106. * @param theBytes array from which to read bytes
  1107. * @param off offset for array
  1108. * @param len max number of bytes to read into array
  1109. * @since 1.3
  1110. */
  1111. public void write( byte[] theBytes, int off, int len ) throws java.io.IOException {
  1112. // Encoding suspended?
  1113. if ( suspendEncoding ) {
  1114. super.out.write( theBytes, off, len );
  1115. return ;
  1116. } // end if: supsended
  1117. for ( int i = 0; i < len; i++ ) {
  1118. write( theBytes[ off + i ] );
  1119. } // end for: each byte written
  1120. } // end write
  1121. /**
  1122. * Method added by PHIL. [Thanks, PHIL. -Rob]
  1123. * This pads the buffer without closing the stream.
  1124. */
  1125. public void flushBase64() throws java.io.IOException {
  1126. if ( position > 0 ) {
  1127. if ( encode ) {
  1128. out.write( encode3to4( b4, buffer, position ) );
  1129. position = 0;
  1130. } // end if: encoding
  1131. else {
  1132. throw new java.io.IOException( "Base64 input not properly padded." );
  1133. } // end else: decoding
  1134. } // end if: buffer partially full
  1135. } // end flush
  1136. /**
  1137. * Flushes and closes (I think, in the superclass) the stream.
  1138. *
  1139. * @since 1.3
  1140. */
  1141. public void close() throws java.io.IOException {
  1142. // 1. Ensure that pending characters are written
  1143. flushBase64();
  1144. // 2. Actually close the stream
  1145. // Base class both flushes and closes.
  1146. super.close();
  1147. buffer = null;
  1148. out = null;
  1149. } // end close
  1150. /**
  1151. * Suspends encoding of the stream.
  1152. * May be helpful if you need to embed a piece of
  1153. * base640-encoded data in a stream.
  1154. *
  1155. * @since 1.5.1
  1156. */
  1157. public void suspendEncoding() throws java.io.IOException {
  1158. flushBase64();
  1159. this.suspendEncoding = true;
  1160. } // end suspendEncoding
  1161. /**
  1162. * Resumes encoding of the stream.
  1163. * May be helpful if you need to embed a piece of
  1164. * base640-encoded data in a stream.
  1165. *
  1166. * @since 1.5.1
  1167. */
  1168. public void resumeEncoding() {
  1169. this.suspendEncoding = false;
  1170. } // end resumeEncoding
  1171. } // end inner class OutputStream
  1172. public static void main (String[] args) {
  1173. String command = args[0];
  1174. System.out.println(command);
  1175. String to_change = args[1];
  1176. System.out.println(to_change);
  1177. String answer = null;
  1178. if ("decode".equals(command)) {
  1179. answer = new String(Base64.decode(to_change));
  1180. }
  1181. else if ("encode".equals(command)) {
  1182. answer = Base64.encodeBytes(to_change.getBytes());
  1183. }
  1184. else {
  1185. System.out.println("invalid command, 'decode' and 'encode' are valid commands");
  1186. System.exit(1);
  1187. }
  1188. System.out.println(answer);
  1189. System.exit(0);
  1190. }
  1191. } // end class Base64