You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Base64.java 51KB

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