KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > freecs > util > HttpAuth


1 package freecs.util;
2
3 import java.util.NoSuchElementException JavaDoc;
4 import java.util.StringTokenizer JavaDoc;
5
6 public class HttpAuth {
7
8 /**
9  * class for parsing http auth username/password combinations
10  * static decode and static encode from library by kevin kelley
11  * (copyright notice see below)
12  */

13
14     public String JavaDoc username;
15     public String JavaDoc password;
16     
17     public static HttpAuth parse(String JavaDoc auth) {
18
19         if ((auth == null) || "".equals(auth)) {
20             return null;
21         }
22
23         StringTokenizer JavaDoc tok;
24
25         if (auth.startsWith("Basic ")) {
26             String JavaDoc decoded = new String JavaDoc(decode((auth.substring(6)).toCharArray()));
27             tok = new StringTokenizer JavaDoc(decoded ,":");
28         } else {
29             String JavaDoc decoded = new String JavaDoc(decode(auth.toCharArray()));
30             tok = new StringTokenizer JavaDoc(decoded, ":");
31         }
32
33         HttpAuth reval = new HttpAuth();
34         try {
35             reval.username = tok.nextToken();
36         } catch (NoSuchElementException JavaDoc e) {
37             reval.username = null;
38         }
39
40         try {
41             reval.password = tok.nextToken();
42         } catch (NoSuchElementException JavaDoc e) {
43             reval.password = null;
44         }
45         return reval;
46         
47     }
48     
49     
50     
51     
52     
53     
54     //////////////////////license & copyright header/////////////////////////
55
// //
56
//Base64 - encode/decode data using the Base64 encoding scheme //
57
// //
58
//Copyright (c) 1998 by Kevin Kelley //
59
// //
60
//This library is free software; you can redistribute it and/or //
61
//modify it under the terms of the GNU Lesser General Public //
62
//License as published by the Free Software Foundation; either //
63
//version 2.1 of the License, or (at your option) any later version. //
64
// //
65
//This library is distributed in the hope that it will be useful, //
66
//but WITHOUT ANY WARRANTY; without even the implied warranty of //
67
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
68
//GNU Lesser General Public License for more details. //
69
// //
70
//You should have received a copy of the GNU Lesser General Public //
71
//License along with this library; if not, write to the Free Software //
72
//Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA //
73
//02111-1307, USA, or contact the author: //
74
// //
75
//Kevin Kelley <kelley@ruralnet.net> - 30718 Rd. 28, La Junta, CO, //
76
//81050 USA. //
77
// //
78
////////////////////end license & copyright header///////////////////////
79

80     
81     /**
82     * returns an array of base64-encoded characters to represent the
83     * passed data array.
84     *
85     * @param data the array of bytes to encode
86     * @return base64-coded character array.
87     */

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

133     public static final byte[] decode(char[] data)
134     {
135         // as our input could contain non-BASE64 data (newlines,
136
// whitespace of any sort, whatever) we must first adjust
137
// our count of USABLE data so that...
138
// (a) we don't misallocate the output array, and
139
// (b) think that we miscalculated our data length
140
// just because of extraneous throw-away junk
141

142         int tempLen = data.length;
143         for( int ix=0; ix<data.length; ix++ )
144         {
145             if( (data[ix] > 255) || codes[ data[ix] ] < 0 )
146                 --tempLen; // ignore non-valid chars and padding
147
}
148         // calculate required length:
149
// -- 3 bytes for every 4 valid base64 chars
150
// -- plus 2 bytes if there are 3 extra base64 chars,
151
// or plus 1 byte if there are 2 extra.
152

153         int len = (tempLen / 4) * 3;
154         if ((tempLen % 4) == 3) len += 2;
155         if ((tempLen % 4) == 2) len += 1;
156
157         byte[] out = new byte[len];
158
159
160
161         int shift = 0; // # of excess bits stored in accum
162
int accum = 0; // excess bits
163
int index = 0;
164
165         // we now go through the entire array (NOT using the 'tempLen' value)
166
for (int ix=0; ix<data.length; ix++)
167         {
168             int value = (data[ix]>255)? -1: codes[ data[ix] ];
169
170             if ( value >= 0 ) // skip over non-code
171
{
172                 accum <<= 6; // bits shift up by 6 each time thru
173
shift += 6; // loop, with new bits being put in
174
accum |= value; // at the bottom.
175
if ( shift >= 8 ) // whenever there are 8 or more shifted in,
176
{
177                     shift -= 8; // write them out (from the top, leaving any
178
out[index++] = // excess at the bottom for next iteration.
179
(byte) ((accum >> shift) & 0xff);
180                 }
181             }
182             // we will also have skipped processing a padding null byte ('=') here;
183
// these are used ONLY for padding to an even length and do not legally
184
// occur as encoded data. for this reason we can ignore the fact that
185
// no index++ operation occurs in that special case: the out[] array is
186
// initialized to all-zero bytes to start with and that works to our
187
// advantage in this combination.
188
}
189
190         // if there is STILL something wrong we just have to throw up now!
191
if( index != out.length)
192         {
193             throw new Error JavaDoc("Miscalculated data length (wrote " + index + " instead of " + out.length + ")");
194         }
195
196         return out;
197     }
198
199
200     //
201
// code characters for values 0..63
202
//
203
private static char[] alphabet =
204         "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
205             .toCharArray();
206
207     //
208
// lookup table for converting base64 characters to value in range 0..63
209
//
210
private static byte[] codes = new byte[256];
211     static {
212         for (int i=0; i<256; i++) codes[i] = -1;
213         for (int i = 'A'; i <= 'Z'; i++) codes[i] = (byte)( i - 'A');
214         for (int i = 'a'; i <= 'z'; i++) codes[i] = (byte)(26 + i - 'a');
215         for (int i = '0'; i <= '9'; i++) codes[i] = (byte)(52 + i - '0');
216         codes['+'] = 62;
217         codes['/'] = 63;
218     }
219
220 }
221
Popular Tags