James Moger
2012-09-10 fabe060d3a435f116128851f828e35c2af5fde67
commit | author | age
773bb6 1 //
JM 2 //  NOTE: The following source code is heavily derived from the
3 //  iHarder.net public domain Base64 library.  See the original at
4 //  http://iharder.sourceforge.net/current/java/base64/
5 //
6
7 package com.gitblit.utils;
8
9 import java.io.UnsupportedEncodingException;
10 import java.text.MessageFormat;
11 import java.util.Arrays;
12
13 /**
14  * Encodes and decodes to and from Base64 notation.
15  * <p>
16  * I am placing this code in the Public Domain. Do with it as you will. This
17  * software comes with no guarantees or warranties but with plenty of
18  * well-wishing instead! Please visit <a
19  * href="http://iharder.net/base64">http://iharder.net/base64</a> periodically
20  * to check for updates or to contribute improvements.
21  * </p>
22  * 
23  * @author Robert Harder
24  * @author rob@iharder.net
25  * @version 2.1, stripped to minimum feature set used by JGit.
26  */
27 public class Base64 {
28     /** The equals sign (=) as a byte. */
29     private final static byte EQUALS_SIGN = (byte) '=';
30
31     /** Indicates equals sign in encoding. */
32     private final static byte EQUALS_SIGN_DEC = -1;
33
34     /** Indicates white space in encoding. */
35     private final static byte WHITE_SPACE_DEC = -2;
36
37     /** Indicates an invalid byte during decoding. */
38     private final static byte INVALID_DEC = -3;
39
40     /** Preferred encoding. */
41     private final static String UTF_8 = "UTF-8";
42
43     /** The 64 valid Base64 values. */
44     private final static byte[] ENC;
45
46     /**
47      * Translates a Base64 value to either its 6-bit reconstruction value or a
48      * negative number indicating some other meaning. The table is only 7 bits
49      * wide, as the 8th bit is discarded during decoding.
50      */
51     private final static byte[] DEC;
52
53     static {
54         try {
55             ENC = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ" //
56                     + "abcdefghijklmnopqrstuvwxyz" //
57                     + "0123456789" //
58                     + "+/" //
59             ).getBytes(UTF_8);
60         } catch (UnsupportedEncodingException uee) {
61             throw new RuntimeException(uee.getMessage(), uee);
62         }
63
64         DEC = new byte[128];
65         Arrays.fill(DEC, INVALID_DEC);
66
67         for (int i = 0; i < 64; i++)
68             DEC[ENC[i]] = (byte) i;
69         DEC[EQUALS_SIGN] = EQUALS_SIGN_DEC;
70
71         DEC['\t'] = WHITE_SPACE_DEC;
72         DEC['\n'] = WHITE_SPACE_DEC;
73         DEC['\r'] = WHITE_SPACE_DEC;
74         DEC[' '] = WHITE_SPACE_DEC;
75     }
76
77     /** Defeats instantiation. */
78     private Base64() {
79         // Suppress empty block warning.
80     }
81
82     /**
83      * Encodes up to three bytes of the array <var>source</var> and writes the
84      * resulting four Base64 bytes to <var>destination</var>. The source and
85      * destination arrays can be manipulated anywhere along their length by
86      * specifying <var>srcOffset</var> and <var>destOffset</var>. This method
87      * does not check to make sure your arrays are large enough to accommodate
88      * <var>srcOffset</var> + 3 for the <var>source</var> array or
89      * <var>destOffset</var> + 4 for the <var>destination</var> array. The
90      * actual number of significant bytes in your array is given by
91      * <var>numSigBytes</var>.
92      * 
93      * @param source
94      *            the array to convert
95      * @param srcOffset
96      *            the index where conversion begins
97      * @param numSigBytes
98      *            the number of significant bytes in your array
99      * @param destination
100      *            the array to hold the conversion
101      * @param destOffset
102      *            the index where output will be put
103      */
104     private static void encode3to4(byte[] source, int srcOffset, int numSigBytes,
105             byte[] destination, int destOffset) {
106         // We have to shift left 24 in order to flush out the 1's that appear
107         // when Java treats a value as negative that is cast from a byte.
108
109         int inBuff = 0;
110         switch (numSigBytes) {
111         case 3:
112             inBuff |= (source[srcOffset + 2] << 24) >>> 24;
113             //$FALL-THROUGH$
114
115         case 2:
116             inBuff |= (source[srcOffset + 1] << 24) >>> 16;
117             //$FALL-THROUGH$
118
119         case 1:
120             inBuff |= (source[srcOffset] << 24) >>> 8;
121         }
122
123         switch (numSigBytes) {
124         case 3:
125             destination[destOffset] = ENC[(inBuff >>> 18)];
126             destination[destOffset + 1] = ENC[(inBuff >>> 12) & 0x3f];
127             destination[destOffset + 2] = ENC[(inBuff >>> 6) & 0x3f];
128             destination[destOffset + 3] = ENC[(inBuff) & 0x3f];
129             break;
130
131         case 2:
132             destination[destOffset] = ENC[(inBuff >>> 18)];
133             destination[destOffset + 1] = ENC[(inBuff >>> 12) & 0x3f];
134             destination[destOffset + 2] = ENC[(inBuff >>> 6) & 0x3f];
135             destination[destOffset + 3] = EQUALS_SIGN;
136             break;
137
138         case 1:
139             destination[destOffset] = ENC[(inBuff >>> 18)];
140             destination[destOffset + 1] = ENC[(inBuff >>> 12) & 0x3f];
141             destination[destOffset + 2] = EQUALS_SIGN;
142             destination[destOffset + 3] = EQUALS_SIGN;
143             break;
144         }
145     }
146
147     /**
148      * Encodes a byte array into Base64 notation.
149      * 
150      * @param source
151      *            The data to convert
152      * @return encoded base64 representation of source.
153      */
154     public static String encodeBytes(byte[] source) {
155         return encodeBytes(source, 0, source.length);
156     }
157
158     /**
159      * Encodes a byte array into Base64 notation.
160      * 
161      * @param source
162      *            The data to convert
163      * @param off
164      *            Offset in array where conversion should begin
165      * @param len
166      *            Length of data to convert
167      * @return encoded base64 representation of source.
168      */
169     public static String encodeBytes(byte[] source, int off, int len) {
170         final int len43 = len * 4 / 3;
171
172         byte[] outBuff = new byte[len43 + ((len % 3) > 0 ? 4 : 0)];
173         int d = 0;
174         int e = 0;
175         int len2 = len - 2;
176
177         for (; d < len2; d += 3, e += 4)
178             encode3to4(source, d + off, 3, outBuff, e);
179
180         if (d < len) {
181             encode3to4(source, d + off, len - d, outBuff, e);
182             e += 4;
183         }
184
185         try {
186             return new String(outBuff, 0, e, UTF_8);
187         } catch (UnsupportedEncodingException uue) {
188             return new String(outBuff, 0, e);
189         }
190     }
191
192     /**
193      * Decodes four bytes from array <var>source</var> and writes the resulting
194      * bytes (up to three of them) to <var>destination</var>. The source and
195      * destination arrays can be manipulated anywhere along their length by
196      * specifying <var>srcOffset</var> and <var>destOffset</var>. This method
197      * does not check to make sure your arrays are large enough to accommodate
198      * <var>srcOffset</var> + 4 for the <var>source</var> array or
199      * <var>destOffset</var> + 3 for the <var>destination</var> array. This
200      * method returns the actual number of bytes that were converted from the
201      * Base64 encoding.
202      * 
203      * @param source
204      *            the array to convert
205      * @param srcOffset
206      *            the index where conversion begins
207      * @param destination
208      *            the array to hold the conversion
209      * @param destOffset
210      *            the index where output will be put
211      * @return the number of decoded bytes converted
212      */
213     private static int decode4to3(byte[] source, int srcOffset, byte[] destination, int destOffset) {
214         // Example: Dk==
215         if (source[srcOffset + 2] == EQUALS_SIGN) {
216             int outBuff = ((DEC[source[srcOffset]] & 0xFF) << 18)
217                     | ((DEC[source[srcOffset + 1]] & 0xFF) << 12);
218             destination[destOffset] = (byte) (outBuff >>> 16);
219             return 1;
220         }
221
222         // Example: DkL=
223         else if (source[srcOffset + 3] == EQUALS_SIGN) {
224             int outBuff = ((DEC[source[srcOffset]] & 0xFF) << 18)
225                     | ((DEC[source[srcOffset + 1]] & 0xFF) << 12)
226                     | ((DEC[source[srcOffset + 2]] & 0xFF) << 6);
227             destination[destOffset] = (byte) (outBuff >>> 16);
228             destination[destOffset + 1] = (byte) (outBuff >>> 8);
229             return 2;
230         }
231
232         // Example: DkLE
233         else {
234             int outBuff = ((DEC[source[srcOffset]] & 0xFF) << 18)
235                     | ((DEC[source[srcOffset + 1]] & 0xFF) << 12)
236                     | ((DEC[source[srcOffset + 2]] & 0xFF) << 6)
237                     | ((DEC[source[srcOffset + 3]] & 0xFF));
238
239             destination[destOffset] = (byte) (outBuff >> 16);
240             destination[destOffset + 1] = (byte) (outBuff >> 8);
241             destination[destOffset + 2] = (byte) (outBuff);
242
243             return 3;
244         }
245     }
246
247     /**
248      * Low-level decoding ASCII characters from a byte array.
249      * 
250      * @param source
251      *            The Base64 encoded data
252      * @param off
253      *            The offset of where to begin decoding
254      * @param len
255      *            The length of characters to decode
256      * @return decoded data
257      * @throws IllegalArgumentException
258      *             the input is not a valid Base64 sequence.
259      */
260     public static byte[] decode(byte[] source, int off, int len) {
261         byte[] outBuff = new byte[len * 3 / 4]; // Upper limit on size of output
262         int outBuffPosn = 0;
263
264         byte[] b4 = new byte[4];
265         int b4Posn = 0;
266
267         for (int i = off; i < off + len; i++) {
268             byte sbiCrop = (byte) (source[i] & 0x7f);
269             byte sbiDecode = DEC[sbiCrop];
270
271             if (EQUALS_SIGN_DEC <= sbiDecode) {
272                 b4[b4Posn++] = sbiCrop;
273                 if (b4Posn > 3) {
274                     outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn);
275                     b4Posn = 0;
276
277                     // If that was the equals sign, break out of 'for' loop
278                     if (sbiCrop == EQUALS_SIGN)
279                         break;
280                 }
281
282             } else if (sbiDecode != WHITE_SPACE_DEC)
283                 throw new IllegalArgumentException(MessageFormat.format(
284                         "bad base64 input character {1} at {0}", i, source[i] & 0xff));
285         }
286
287         if (outBuff.length == outBuffPosn)
288             return outBuff;
289
290         byte[] out = new byte[outBuffPosn];
291         System.arraycopy(outBuff, 0, out, 0, outBuffPosn);
292         return out;
293     }
294
295     /**
296      * Decodes data from Base64 notation.
297      * 
298      * @param s
299      *            the string to decode
300      * @return the decoded data
301      */
302     public static byte[] decode(String s) {
303         byte[] bytes;
304         try {
305             bytes = s.getBytes(UTF_8);
306         } catch (UnsupportedEncodingException uee) {
307             bytes = s.getBytes();
308         }
309         return decode(bytes, 0, bytes.length);
310     }
311 }