Guest User

Base64.java

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