KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > jonas > security > realm > lib > Base64


1 /**
2  * Base64 - encode/decode data using the Base64 encoding scheme
3  * Copyright (c) 1998 by Kevin Kelley
4  * Contact: Kevin Kelley <kelley@ruralnet.net>
5  * 30718 Rd. 28, La Junta, CO, 81050 USA.
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or 1any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
20  * USA
21  *
22  */

23
24 package org.objectweb.jonas.security.realm.lib;
25
26 /**
27  * Provides encoding of raw bytes to base64-encoded characters, and
28  * decoding of base64 characters to raw bytes.
29  *
30  * @author Kevin Kelley (kelley@ruralnet.net)
31  * @version 1.3
32  * @date 06 August 1998
33  * @modified 14 February 2000
34  * @modified 22 September 2000
35  */

36 public class Base64 {
37
38     /**
39      * code characters for values 0..63
40      */

41     private static char[] alphabet =
42         "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
43         .toCharArray();
44
45     /**
46      * lookup table for converting base64 characters to value in range 0..63
47      */

48     private static byte[] codes = new byte[256];
49
50     static {
51         for (int i = 0; i < 256; i++) {
52             codes[i] = -1;
53         }
54         for (int i = 'A'; i <= 'Z'; i++) {
55             codes[i] = (byte) (i - 'A');
56         }
57         for (int i = 'a'; i <= 'z'; i++) {
58             codes[i] = (byte) (26 + i - 'a');
59         }
60         for (int i = '0'; i <= '9'; i++) {
61             codes[i] = (byte) (52 + i - '0');
62         }
63         codes['+'] = 62;
64         codes['/'] = 63;
65     }
66
67
68
69     /**
70      * returns an array of base64-encoded characters to represent the
71      * passed data array.
72      *
73      * @param data the array of bytes to encode
74      * @return base64-coded character array.
75      */

76     public static char[] encode(byte[] data) {
77         char[] out = new char[((data.length + 2) / 3) * 4];
78
79         //
80
// 3 bytes encode to 4 chars. Output is always an even
81
// multiple of 4 characters.
82
//
83
for (int i = 0, index = 0; i < data.length; i += 3, index += 4) {
84             boolean quad = false;
85             boolean trip = false;
86
87             int val = (0xFF & (int) data[i]);
88             val <<= 8;
89             if ((i + 1) < data.length) {
90                 val |= (0xFF & (int) data[i + 1]);
91                 trip = true;
92             }
93             val <<= 8;
94             if ((i + 2) < data.length) {
95                 val |= (0xFF & (int) data[i + 2]);
96                 quad = true;
97             }
98             out[index + 3] = alphabet[(quad ? (val & 0x3F) : 64)];
99             val >>= 6;
100             out[index + 2] = alphabet[(trip ? (val & 0x3F) : 64)];
101             val >>= 6;
102             out[index + 1] = alphabet[val & 0x3F];
103             val >>= 6;
104             out[index + 0] = alphabet[val & 0x3F];
105         }
106         return out;
107     }
108
109     /**
110      * Decodes a BASE-64 encoded stream to recover the original
111      * data. White space before and after will be trimmed away,
112      * but no other manipulation of the input will be performed.
113      *
114      * As of version 1.2 this method will properly handle input
115      * containing junk characters (newlines and the like) rather
116      * than throwing an error. It does this by pre-parsing the
117      * input and generating from that a count of VALID input
118      * characters.
119      * @param data BASE-64 encoded stream
120      * @return original data
121      **/

122     public static byte[] decode(char[] data) {
123         // as our input could contain non-BASE64 data (newlines,
124
// whitespace of any sort, whatever) we must first adjust
125
// our count of USABLE data so that...
126
// (a) we don't misallocate the output array, and
127
// (b) think that we miscalculated our data length
128
// just because of extraneous throw-away junk
129

130         int tempLen = data.length;
131         for (int ix = 0; ix < data.length; ix++) {
132             if ((data[ix] > 255) || codes[ data[ix] ] < 0) {
133                 --tempLen; // ignore non-valid chars and padding
134
}
135         }
136         // calculate required length:
137
// -- 3 bytes for every 4 valid base64 chars
138
// -- plus 2 bytes if there are 3 extra base64 chars,
139
// or plus 1 byte if there are 2 extra.
140

141         int len = (tempLen / 4) * 3;
142         if ((tempLen % 4) == 3) {
143             len += 2;
144         }
145         if ((tempLen % 4) == 2) {
146             len += 1;
147         }
148
149         byte[] out = new byte[len];
150
151
152
153         int shift = 0; // # of excess bits stored in accum
154
int accum = 0; // excess bits
155
int index = 0;
156
157         // we now go through the entire array (NOT using the 'tempLen' value)
158
for (int ix = 0; ix < data.length; ix++) {
159             int value = (data[ix] > 255) ? -1 : codes[ data[ix] ];
160
161             if (value >= 0) { // skip over non-code
162
accum <<= 6; // bits shift up by 6 each time thru
163
shift += 6; // loop, with new bits being put in
164
accum |= value; // at the bottom.
165
if (shift >= 8) { // whenever there are 8 or more shifted in,
166
shift -= 8; // write them out (from the top, leaving any
167
out[index++] = // excess at the bottom for next iteration.
168
(byte) ((accum >> shift) & 0xff);
169                 }
170             }
171             // we will also have skipped processing a padding null byte ('=') here;
172
// these are used ONLY for padding to an even length and do not legally
173
// occur as encoded data. for this reason we can ignore the fact that
174
// no index++ operation occurs in that special case: the out[] array is
175
// initialized to all-zero bytes to start with and that works to our
176
// advantage in this combination.
177
}
178
179         // if there is STILL something wrong we just have to throw up now!
180
if (index != out.length) {
181             throw new Error JavaDoc("Miscalculated data length (wrote " + index + " instead of " + out.length + ")");
182         }
183
184         return out;
185     }
186
187
188
189 }
190
Popular Tags