Source Code Cross Referenced for Base64.java in  » Web-Framework » rife-1.6.1 » com » uwyn » rife » tools » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Web Framework » rife 1.6.1 » com.uwyn.rife.tools 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        package com.uwyn.rife.tools;
002:
003:        import java.util.Arrays;
004:
005:        /** A very fast and memory efficient class to encode and decode to and from BASE64 in full accordance
006:         * with RFC 2045.<br><br>
007:         * On Windows XP sp1 with 1.4.2_04 and later ;), this encoder and decoder is about 10 times faster
008:         * on small arrays (10 - 1000 bytes) and 2-3 times as fast on larger arrays (10000 - 1000000 bytes)
009:         * compared to <code>sun.misc.Encoder()/Decoder()</code>.<br><br>
010:         *
011:         * On byte arrays the encoder is about 20% faster than Jakarta Commons Base64 Codec for encode and
012:         * about 50% faster for decoding large arrays. This implementation is about twice as fast on very small
013:         * arrays (&lt 30 bytes). If source/destination is a <code>String</code> this
014:         * version is about three times as fast due to the fact that the Commons Codec result has to be recoded
015:         * to a <code>String</code> from <code>byte[]</code>, which is very expensive.<br><br>
016:         *
017:         * This encode/decode algorithm doesn't create any temporary arrays as many other codecs do, it only
018:         * allocates the resulting array. This produces less garbage and it is possible to handle arrays twice
019:         * as large as algorithms that create a temporary array. (E.g. Jakarta Commons Codec). It is unknown
020:         * whether Sun's <code>sun.misc.Encoder()/Decoder()</code> produce temporary arrays but since performance
021:         * is quite low it probably does.<br><br>
022:         *
023:         * The encoder produces the same output as the Sun one except that the Sun's encoder appends
024:         * a trailing line separator if the last character isn't a pad. Unclear why but it only adds to the
025:         * length and is probably a side effect. Both are in conformance with RFC 2045 though.<br>
026:         * Commons codec seem to always att a trailing line separator.<br><br>
027:         *
028:         * <b>Note!</b>
029:         * The encode/decode method pairs (types) come in three versions with the <b>exact</b> same algorithm and
030:         * thus a lot of code redundancy. This is to not create any temporary arrays for transcoding to/from different
031:         * format types. The methods not used can simply be commented out.<br><br>
032:         *
033:         * There is also a "fast" version of all decode methods that works the same way as the normal ones, but
034:         * har a few demands on the decoded input. Normally though, these fast verions should be used if the source if
035:         * the input is known and it hasn't bee tampered with.<br><br>
036:         *
037:         * If you find the code useful or you find a bug, please send me a note at base64 @ miginfocom . com.
038:         *
039:         * Licence (BSD):
040:         * ==============
041:         *
042:         * Copyright (c) 2004, Mikael Grev, MiG InfoCom AB. (base64 @ miginfocom . com)
043:         * All rights reserved.
044:         *
045:         * Redistribution and use in source and binary forms, with or without modification,
046:         * are permitted provided that the following conditions are met:
047:         * Redistributions of source code must retain the above copyright notice, this list
048:         * of conditions and the following disclaimer.
049:         * Redistributions in binary form must reproduce the above copyright notice, this
050:         * list of conditions and the following disclaimer in the documentation and/or other
051:         * materials provided with the distribution.
052:         * Neither the name of the MiG InfoCom AB nor the names of its contributors may be
053:         * used to endorse or promote products derived from this software without specific
054:         * prior written permission.
055:         *
056:         * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
057:         * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
058:         * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
059:         * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
060:         * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
061:         * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
062:         * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
063:         * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
064:         * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
065:         * OF SUCH DAMAGE.
066:         *
067:         * @version 2.2
068:         * @author Mikael Grev
069:         *         Date: 2004-aug-02
070:         *         Time: 11:31:11
071:         */
072:
073:        public final class Base64 {
074:            private static final char[] CA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
075:                    .toCharArray();
076:            private static final int[] IA = new int[256];
077:            static {
078:                Arrays.fill(IA, -1);
079:                for (int i = 0, iS = CA.length; i < iS; i++)
080:                    IA[CA[i]] = i;
081:                IA['='] = 0;
082:            }
083:
084:            // ****************************************************************************************
085:            // *  char[] version
086:            // ****************************************************************************************
087:
088:            /** Encodes a raw byte array into a BASE64 <code>char[]</code> representation i accordance with RFC 2045.
089:             * @param sArr The bytes to convert. If <code>null</code> or length 0 an empty array will be returned.
090:             * @param lineSep Optional "\r\n" after 76 characters, unless end of file.<br>
091:             * No line separator will be in breach of RFC 2045 which specifies max 76 per line but will be a
092:             * little faster.
093:             * @return A BASE64 encoded array. Never <code>null</code>.
094:             */
095:            public static char[] encodeToChar(byte[] sArr, boolean lineSep) {
096:                // Check special case
097:                int sLen = sArr != null ? sArr.length : 0;
098:                if (sLen == 0)
099:                    return new char[0];
100:
101:                int eLen = (sLen / 3) * 3; // Length of even 24-bits.
102:                int cCnt = ((sLen - 1) / 3 + 1) << 2; // Returned character count
103:                int dLen = cCnt + (lineSep ? (cCnt - 1) / 76 << 1 : 0); // Length of returned array
104:                char[] dArr = new char[dLen];
105:
106:                // Encode even 24-bits
107:                for (int s = 0, d = 0, cc = 0; s < eLen;) {
108:                    // Copy next three bytes into lower 24 bits of int, paying attension to sign.
109:                    int i = (sArr[s++] & 0xff) << 16 | (sArr[s++] & 0xff) << 8
110:                            | (sArr[s++] & 0xff);
111:
112:                    // Encode the int into four chars
113:                    dArr[d++] = CA[(i >>> 18) & 0x3f];
114:                    dArr[d++] = CA[(i >>> 12) & 0x3f];
115:                    dArr[d++] = CA[(i >>> 6) & 0x3f];
116:                    dArr[d++] = CA[i & 0x3f];
117:
118:                    // Add optional line separator
119:                    if (lineSep && ++cc == 19 && d < dLen - 2) {
120:                        dArr[d++] = '\r';
121:                        dArr[d++] = '\n';
122:                        cc = 0;
123:                    }
124:                }
125:
126:                // Pad and encode last bits if source isn't even 24 bits.
127:                int left = sLen - eLen; // 0 - 2.
128:                if (left > 0) {
129:                    // Prepare the int
130:                    int i = ((sArr[eLen] & 0xff) << 10)
131:                            | (left == 2 ? ((sArr[sLen - 1] & 0xff) << 2) : 0);
132:
133:                    // Set last four chars
134:                    dArr[dLen - 4] = CA[i >> 12];
135:                    dArr[dLen - 3] = CA[(i >>> 6) & 0x3f];
136:                    dArr[dLen - 2] = left == 2 ? CA[i & 0x3f] : '=';
137:                    dArr[dLen - 1] = '=';
138:                }
139:                return dArr;
140:            }
141:
142:            /** Decodes a BASE64 encoded char array. All illegal characters will be ignored and can handle both arrays with
143:             * and without line separators.
144:             * @param sArr The source array. <code>null</code> or length 0 will return an empty array.
145:             * @return The decoded array of bytes. May be of length 0. Will be <code>null</code> if the legal characters
146:             * (including '=') isn't divideable by 4.  (I.e. definitely corrupted).
147:             */
148:            public static byte[] decode(char[] sArr) {
149:                // Check special case
150:                int sLen = sArr != null ? sArr.length : 0;
151:                if (sLen == 0)
152:                    return new byte[0];
153:
154:                // Count illegal characters (including '\r', '\n') to know what size the returned array will be,
155:                // so we don't have to reallocate & copy it later.
156:                int sepCnt = 0; // Number of separator characters. (Actually illegal characters, but that's a bonus...)
157:                for (int i = 0; i < sLen; i++)
158:                    // If input is "pure" (I.e. no line separators or illegal chars) base64 this loop can be commented out.
159:                    if (IA[sArr[i]] < 0)
160:                        sepCnt++;
161:
162:                // Check so that legal chars (including '=') are evenly divideable by 4 as specified in RFC 2045.
163:                if ((sLen - sepCnt) % 4 != 0)
164:                    return null;
165:
166:                int pad = 0;
167:                for (int i = sLen; i > 1 && IA[sArr[--i]] <= 0;)
168:                    if (sArr[i] == '=')
169:                        pad++;
170:
171:                int len = ((sLen - sepCnt) * 6 >> 3) - pad;
172:
173:                byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
174:
175:                for (int s = 0, d = 0; d < len;) {
176:                    // Assemble three bytes into an int from four "valid" characters.
177:                    int i = 0;
178:                    for (int j = 0; j < 4; j++) { // j only increased if a valid char was found.
179:                        int c = IA[sArr[s++]];
180:                        if (c >= 0)
181:                            i |= c << (18 - j * 6);
182:                        else
183:                            j--;
184:                    }
185:                    // Add the bytes
186:                    dArr[d++] = (byte) (i >> 16);
187:                    if (d < len) {
188:                        dArr[d++] = (byte) (i >> 8);
189:                        if (d < len)
190:                            dArr[d++] = (byte) i;
191:                    }
192:                }
193:                return dArr;
194:            }
195:
196:            /** Decodes a BASE64 encoded char array that is known to be resonably well formatted. The method is about twice as
197:             * fast as {@link #decode(char[])}. The preconditions are:<br>
198:             * + The array must have a line length of 76 chars OR no line separators at all (one line).<br>
199:             * + Line separator must be "\r\n", as specified in RFC 2045
200:             * + The array must not contain illegal characters within the encoded string<br>
201:             * + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.<br>
202:             * @param sArr The source array. Length 0 will return an empty array. <code>null</code> will throw an exception.
203:             * @return The decoded array of bytes. May be of length 0.
204:             */
205:            public byte[] decodeFast(char[] sArr) {
206:                // Check special case
207:                int sLen = sArr.length;
208:                if (sLen == 0)
209:                    return new byte[0];
210:
211:                int sIx = 0, eIx = sLen - 1; // Start and end index after trimming.
212:
213:                // Trim illegal chars from start
214:                while (sIx < eIx && IA[sArr[sIx]] < 0)
215:                    sIx++;
216:
217:                // Trim illegal chars from end
218:                while (eIx > 0 && IA[sArr[eIx]] < 0)
219:                    eIx--;
220:
221:                // get the padding count (=) (0, 1 or 2)
222:                int pad = sArr[eIx] == '=' ? (sArr[eIx - 1] == '=' ? 2 : 1) : 0; // Count '=' at end.
223:                int cCnt = eIx - sIx + 1; // Content count including possible separators
224:                int sepCnt = sLen > 76 ? (sArr[76] == '\r' ? cCnt / 78 : 0) << 1
225:                        : 0;
226:
227:                int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes
228:                byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
229:
230:                // Decode all but the last 0 - 2 bytes.
231:                int d = 0;
232:                for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) {
233:                    // Assemble three bytes into an int from four "valid" characters.
234:                    int i = IA[sArr[sIx++]] << 18 | IA[sArr[sIx++]] << 12
235:                            | IA[sArr[sIx++]] << 6 | IA[sArr[sIx++]];
236:
237:                    // Add the bytes
238:                    dArr[d++] = (byte) (i >> 16);
239:                    dArr[d++] = (byte) (i >> 8);
240:                    dArr[d++] = (byte) i;
241:
242:                    // If line separator, jump over it.
243:                    if (sepCnt > 0 && ++cc == 19) {
244:                        sIx += 2;
245:                        cc = 0;
246:                    }
247:                }
248:
249:                if (d < len) {
250:                    // Decode last 1-3 bytes (incl '=') into 1-3 bytes
251:                    int i = 0;
252:                    for (int j = 0; sIx <= eIx - pad; j++)
253:                        i |= IA[sArr[sIx++]] << (18 - j * 6);
254:
255:                    for (int r = 16; d < len; r -= 8)
256:                        dArr[d++] = (byte) (i >> r);
257:                }
258:
259:                return dArr;
260:            }
261:
262:            // ****************************************************************************************
263:            // *  byte[] version
264:            // ****************************************************************************************
265:
266:            /** Encodes a raw byte array into a BASE64 <code>byte[]</code> representation i accordance with RFC 2045.
267:             * @param sArr The bytes to convert. If <code>null</code> or length 0 an empty array will be returned.
268:             * @param lineSep Optional "\r\n" after 76 characters, unless end of file.<br>
269:             * No line separator will be in breach of RFC 2045 which specifies max 76 per line but will be a
270:             * little faster.
271:             * @return A BASE64 encoded array. Never <code>null</code>.
272:             */
273:            public static byte[] encodeToByte(byte[] sArr, boolean lineSep) {
274:                // Check special case
275:                int sLen = sArr != null ? sArr.length : 0;
276:                if (sLen == 0)
277:                    return new byte[0];
278:
279:                int eLen = (sLen / 3) * 3; // Length of even 24-bits.
280:                int cCnt = ((sLen - 1) / 3 + 1) << 2; // Returned character count
281:                int dLen = cCnt + (lineSep ? (cCnt - 1) / 76 << 1 : 0); // Length of returned array
282:                byte[] dArr = new byte[dLen];
283:
284:                // Encode even 24-bits
285:                for (int s = 0, d = 0, cc = 0; s < eLen;) {
286:                    // Copy next three bytes into lower 24 bits of int, paying attension to sign.
287:                    int i = (sArr[s++] & 0xff) << 16 | (sArr[s++] & 0xff) << 8
288:                            | (sArr[s++] & 0xff);
289:
290:                    // Encode the int into four chars
291:                    dArr[d++] = (byte) CA[(i >>> 18) & 0x3f];
292:                    dArr[d++] = (byte) CA[(i >>> 12) & 0x3f];
293:                    dArr[d++] = (byte) CA[(i >>> 6) & 0x3f];
294:                    dArr[d++] = (byte) CA[i & 0x3f];
295:
296:                    // Add optional line separator
297:                    if (lineSep && ++cc == 19 && d < dLen - 2) {
298:                        dArr[d++] = '\r';
299:                        dArr[d++] = '\n';
300:                        cc = 0;
301:                    }
302:                }
303:
304:                // Pad and encode last bits if source isn't an even 24 bits.
305:                int left = sLen - eLen; // 0 - 2.
306:                if (left > 0) {
307:                    // Prepare the int
308:                    int i = ((sArr[eLen] & 0xff) << 10)
309:                            | (left == 2 ? ((sArr[sLen - 1] & 0xff) << 2) : 0);
310:
311:                    // Set last four chars
312:                    dArr[dLen - 4] = (byte) CA[i >> 12];
313:                    dArr[dLen - 3] = (byte) CA[(i >>> 6) & 0x3f];
314:                    dArr[dLen - 2] = left == 2 ? (byte) CA[i & 0x3f]
315:                            : (byte) '=';
316:                    dArr[dLen - 1] = '=';
317:                }
318:                return dArr;
319:            }
320:
321:            /** Decodes a BASE64 encoded byte array. All illegal characters will be ignored and can handle both arrays with
322:             * and without line separators.
323:             * @param sArr The source array. Length 0 will return an empty array. <code>null</code> will throw an exception.
324:             * @return The decoded array of bytes. May be of length 0. Will be <code>null</code> if the legal characters
325:             * (including '=') isn't divideable by 4. (I.e. definitely corrupted).
326:             */
327:            public static byte[] decode(byte[] sArr) {
328:                // Check special case
329:                int sLen = sArr.length;
330:
331:                // Count illegal characters (including '\r', '\n') to know what size the returned array will be,
332:                // so we don't have to reallocate & copy it later.
333:                int sepCnt = 0; // Number of separator characters. (Actually illegal characters, but that's a bonus...)
334:                for (int i = 0; i < sLen; i++)
335:                    // If input is "pure" (I.e. no line separators or illegal chars) base64 this loop can be commented out.
336:                    if (IA[sArr[i] & 0xff] < 0)
337:                        sepCnt++;
338:
339:                // Check so that legal chars (including '=') are evenly divideable by 4 as specified in RFC 2045.
340:                if ((sLen - sepCnt) % 4 != 0)
341:                    return null;
342:
343:                int pad = 0;
344:                for (int i = sLen; i > 1 && IA[sArr[--i] & 0xff] <= 0;)
345:                    if (sArr[i] == '=')
346:                        pad++;
347:
348:                int len = ((sLen - sepCnt) * 6 >> 3) - pad;
349:
350:                byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
351:
352:                for (int s = 0, d = 0; d < len;) {
353:                    // Assemble three bytes into an int from four "valid" characters.
354:                    int i = 0;
355:                    for (int j = 0; j < 4; j++) { // j only increased if a valid char was found.
356:                        int c = IA[sArr[s++] & 0xff];
357:                        if (c >= 0)
358:                            i |= c << (18 - j * 6);
359:                        else
360:                            j--;
361:                    }
362:
363:                    // Add the bytes
364:                    dArr[d++] = (byte) (i >> 16);
365:                    if (d < len) {
366:                        dArr[d++] = (byte) (i >> 8);
367:                        if (d < len)
368:                            dArr[d++] = (byte) i;
369:                    }
370:                }
371:
372:                return dArr;
373:            }
374:
375:            /** Decodes a BASE64 encoded byte array that is known to be resonably well formatted. The method is about twice as
376:             * fast as {@link #decode(byte[])}. The preconditions are:<br>
377:             * + The array must have a line length of 76 chars OR no line separators at all (one line).<br>
378:             * + Line separator must be "\r\n", as specified in RFC 2045
379:             * + The array must not contain illegal characters within the encoded string<br>
380:             * + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.<br>
381:             * @param sArr The source array. Length 0 will return an empty array. <code>null</code> will throw an exception.
382:             * @return The decoded array of bytes. May be of length 0.
383:             */
384:            public static byte[] decodeFast(byte[] sArr) {
385:                // Check special case
386:                int sLen = sArr.length;
387:                if (sLen == 0)
388:                    return new byte[0];
389:
390:                int sIx = 0, eIx = sLen - 1; // Start and end index after trimming.
391:
392:                // Trim illegal chars from start
393:                while (sIx < eIx && IA[sArr[sIx] & 0xff] < 0)
394:                    sIx++;
395:
396:                // Trim illegal chars from end
397:                while (eIx > 0 && IA[sArr[eIx] & 0xff] < 0)
398:                    eIx--;
399:
400:                // get the padding count (=) (0, 1 or 2)
401:                int pad = sArr[eIx] == '=' ? (sArr[eIx - 1] == '=' ? 2 : 1) : 0; // Count '=' at end.
402:                int cCnt = eIx - sIx + 1; // Content count including possible separators
403:                int sepCnt = sLen > 76 ? (sArr[76] == '\r' ? cCnt / 78 : 0) << 1
404:                        : 0;
405:
406:                int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes
407:                byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
408:
409:                // Decode all but the last 0 - 2 bytes.
410:                int d = 0;
411:                for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) {
412:                    // Assemble three bytes into an int from four "valid" characters.
413:                    int i = IA[sArr[sIx++]] << 18 | IA[sArr[sIx++]] << 12
414:                            | IA[sArr[sIx++]] << 6 | IA[sArr[sIx++]];
415:
416:                    // Add the bytes
417:                    dArr[d++] = (byte) (i >> 16);
418:                    dArr[d++] = (byte) (i >> 8);
419:                    dArr[d++] = (byte) i;
420:
421:                    // If line separator, jump over it.
422:                    if (sepCnt > 0 && ++cc == 19) {
423:                        sIx += 2;
424:                        cc = 0;
425:                    }
426:                }
427:
428:                if (d < len) {
429:                    // Decode last 1-3 bytes (incl '=') into 1-3 bytes
430:                    int i = 0;
431:                    for (int j = 0; sIx <= eIx - pad; j++)
432:                        i |= IA[sArr[sIx++]] << (18 - j * 6);
433:
434:                    for (int r = 16; d < len; r -= 8)
435:                        dArr[d++] = (byte) (i >> r);
436:                }
437:
438:                return dArr;
439:            }
440:
441:            // ****************************************************************************************
442:            // * String version
443:            // ****************************************************************************************
444:
445:            /** Encodes a raw byte array into a BASE64 <code>String</code> representation i accordance with RFC 2045.
446:             * @param sArr The bytes to convert. If <code>null</code> or length 0 an empty array will be returned.
447:             * @param lineSep Optional "\r\n" after 76 characters, unless end of file.<br>
448:             * No line separator will be in breach of RFC 2045 which specifies max 76 per line but will be a
449:             * little faster.
450:             * @return A BASE64 encoded array. Never <code>null</code>.
451:             */
452:            public static String encodeToString(byte[] sArr, boolean lineSep) {
453:                // Reuse char[] since we can't create a String incrementally anyway and StringBuffer/Builder would be slower.
454:                return new String(encodeToChar(sArr, lineSep));
455:            }
456:
457:            /** Decodes a BASE64 encoded <code>String</code>. All illegal characters will be ignored and can handle both strings with
458:             * and without line separators.<br>
459:             * <b>Note!</b> It can be up to about 2x the speed to call <code>decode(str.toCharArray())</code> instead. That
460:             * will create a temporary array though. This version will use <code>str.charAt(i)</code> to iterate the string.
461:             * @param str The source string. <code>null</code> or length 0 will return an empty array.
462:             * @return The decoded array of bytes. May be of length 0. Will be <code>null</code> if the legal characters
463:             * (including '=') isn't divideable by 4.  (I.e. definitely corrupted).
464:             */
465:            public static byte[] decode(String str) {
466:                // Check special case
467:                int sLen = str != null ? str.length() : 0;
468:                if (sLen == 0)
469:                    return new byte[0];
470:
471:                // Count illegal characters (including '\r', '\n') to know what size the returned array will be,
472:                // so we don't have to reallocate & copy it later.
473:                int sepCnt = 0; // Number of separator characters. (Actually illegal characters, but that's a bonus...)
474:                for (int i = 0; i < sLen; i++)
475:                    // If input is "pure" (I.e. no line separators or illegal chars) base64 this loop can be commented out.
476:                    if (IA[str.charAt(i)] < 0)
477:                        sepCnt++;
478:
479:                // Check so that legal chars (including '=') are evenly divideable by 4 as specified in RFC 2045.
480:                if ((sLen - sepCnt) % 4 != 0)
481:                    return null;
482:
483:                // Count '=' at end
484:                int pad = 0;
485:                for (int i = sLen; i > 1 && IA[str.charAt(--i)] <= 0;)
486:                    if (str.charAt(i) == '=')
487:                        pad++;
488:
489:                int len = ((sLen - sepCnt) * 6 >> 3) - pad;
490:
491:                byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
492:
493:                for (int s = 0, d = 0; d < len;) {
494:                    // Assemble three bytes into an int from four "valid" characters.
495:                    int i = 0;
496:                    for (int j = 0; j < 4; j++) { // j only increased if a valid char was found.
497:                        int c = IA[str.charAt(s++)];
498:                        if (c >= 0)
499:                            i |= c << (18 - j * 6);
500:                        else
501:                            j--;
502:                    }
503:                    // Add the bytes
504:                    dArr[d++] = (byte) (i >> 16);
505:                    if (d < len) {
506:                        dArr[d++] = (byte) (i >> 8);
507:                        if (d < len)
508:                            dArr[d++] = (byte) i;
509:                    }
510:                }
511:                return dArr;
512:            }
513:
514:            /** Decodes a BASE64 encoded string that is known to be resonably well formatted. The method is about twice as
515:             * fast as {@link #decode(String)}. The preconditions are:<br>
516:             * + The array must have a line length of 76 chars OR no line separators at all (one line).<br>
517:             * + Line separator must be "\r\n", as specified in RFC 2045
518:             * + The array must not contain illegal characters within the encoded string<br>
519:             * + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.<br>
520:             * @param s The source string. Length 0 will return an empty array. <code>null</code> will throw an exception.
521:             * @return The decoded array of bytes. May be of length 0.
522:             */
523:            public static byte[] decodeFast(String s) {
524:                // Check special case
525:                int sLen = s.length();
526:                if (sLen == 0)
527:                    return new byte[0];
528:
529:                int sIx = 0, eIx = sLen - 1; // Start and end index after trimming.
530:
531:                // Trim illegal chars from start
532:                while (sIx < eIx && IA[s.charAt(sIx) & 0xff] < 0)
533:                    sIx++;
534:
535:                // Trim illegal chars from end
536:                while (eIx > 0 && IA[s.charAt(eIx) & 0xff] < 0)
537:                    eIx--;
538:
539:                // get the padding count (=) (0, 1 or 2)
540:                int pad = s.charAt(eIx) == '=' ? (s.charAt(eIx - 1) == '=' ? 2
541:                        : 1) : 0; // Count '=' at end.
542:                int cCnt = eIx - sIx + 1; // Content count including possible separators
543:                int sepCnt = sLen > 76 ? (s.charAt(76) == '\r' ? cCnt / 78 : 0) << 1
544:                        : 0;
545:
546:                int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes
547:                byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
548:
549:                // Decode all but the last 0 - 2 bytes.
550:                int d = 0;
551:                for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) {
552:                    // Assemble three bytes into an int from four "valid" characters.
553:                    int i = IA[s.charAt(sIx++)] << 18
554:                            | IA[s.charAt(sIx++)] << 12
555:                            | IA[s.charAt(sIx++)] << 6 | IA[s.charAt(sIx++)];
556:
557:                    // Add the bytes
558:                    dArr[d++] = (byte) (i >> 16);
559:                    dArr[d++] = (byte) (i >> 8);
560:                    dArr[d++] = (byte) i;
561:
562:                    // If line separator, jump over it.
563:                    if (sepCnt > 0 && ++cc == 19) {
564:                        sIx += 2;
565:                        cc = 0;
566:                    }
567:                }
568:
569:                if (d < len) {
570:                    // Decode last 1-3 bytes (incl '=') into 1-3 bytes
571:                    int i = 0;
572:                    for (int j = 0; sIx <= eIx - pad; j++)
573:                        i |= IA[s.charAt(sIx++)] << (18 - j * 6);
574:
575:                    for (int r = 16; d < len; r -= 8)
576:                        dArr[d++] = (byte) (i >> r);
577:                }
578:
579:                return dArr;
580:            }
581:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.