KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > javacoding > jspider > core > util > Base64Encoder


1 package net.javacoding.jspider.core.util;
2
3
4 /**
5  * This class is derived from the one found in the JavaWorld.com article
6  * http://www.javaworld.com/javaworld/javatips/jw-javatip36-p2.html
7  *
8  * $Id: Base64Encoder.java,v 1.2 2003/02/11 17:27:04 vanrogu Exp $
9  *
10  */

11 public abstract class Base64Encoder {
12
13     public final static String JavaDoc base64Encode(String JavaDoc strInput) {
14         if (strInput == null) return null;
15
16         byte byteData[] = new byte[strInput.length()];
17         byteData = strInput.getBytes();
18         return new String JavaDoc(base64Encode(byteData));
19     }
20
21     public final static byte[] base64Encode(byte[] byteData) {
22         if (byteData == null) return null;
23         int iSrcIdx; // index into source (byteData)
24
int iDestIdx; // index into destination (byteDest)
25
byte byteDest[] = new byte[((byteData.length + 2) / 3) * 4];
26         for (iSrcIdx = 0, iDestIdx = 0; iSrcIdx < byteData.length - 2; iSrcIdx += 3) {
27             byteDest[iDestIdx++] = (byte) ((byteData[iSrcIdx] >>> 2) & 077);
28             byteDest[iDestIdx++] = (byte) ((byteData[iSrcIdx + 1] >>> 4) & 017 |
29                     (byteData[iSrcIdx] << 4) & 077);
30             byteDest[iDestIdx++] = (byte) ((byteData[iSrcIdx + 2] >>> 6) & 003 |
31                     (byteData[iSrcIdx + 1] << 2) & 077);
32             byteDest[iDestIdx++] = (byte) (byteData[iSrcIdx + 2] & 077);
33         }
34
35         if (iSrcIdx < byteData.length) {
36             byteDest[iDestIdx++] = (byte) ((byteData[iSrcIdx] >>> 2) & 077);
37             if (iSrcIdx < byteData.length - 1) {
38                 byteDest[iDestIdx++] = (byte) ((byteData[iSrcIdx + 1] >>> 4) & 017 |
39                         (byteData[iSrcIdx] << 4) & 077);
40                 byteDest[iDestIdx++] = (byte) ((byteData[iSrcIdx + 1] << 2) & 077);
41             } else
42                 byteDest[iDestIdx++] = (byte) ((byteData[iSrcIdx] << 4) & 077);
43         }
44
45         for (iSrcIdx = 0; iSrcIdx < iDestIdx; iSrcIdx++) {
46             if (byteDest[iSrcIdx] < 26)
47                 byteDest[iSrcIdx] = (byte) (byteDest[iSrcIdx] + 'A');
48             else if (byteDest[iSrcIdx] < 52)
49                 byteDest[iSrcIdx] = (byte) (byteDest[iSrcIdx] + 'a' - 26);
50             else if (byteDest[iSrcIdx] < 62)
51                 byteDest[iSrcIdx] = (byte) (byteDest[iSrcIdx] + '0' - 52);
52             else if (byteDest[iSrcIdx] < 63)
53                 byteDest[iSrcIdx] = '+';
54             else
55                 byteDest[iSrcIdx] = '/';
56         }
57
58         for (; iSrcIdx < byteDest.length; iSrcIdx++)
59             byteDest[iSrcIdx] = '=';
60         return byteDest;
61     }
62 }
Popular Tags