KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > security > Base64Encoder


1 /*
2 * JBoss, the OpenSource J2EE webOS
3 *
4 * Distributable under LGPL license.
5 * See terms of license at gnu.org.
6 */

7
8 package org.jboss.security; // for the time being ...
9

10 import java.io.ByteArrayInputStream JavaDoc;
11 import java.io.ByteArrayOutputStream JavaDoc;
12 import java.io.IOException JavaDoc;
13 import java.io.InputStream JavaDoc;
14 import java.io.OutputStream JavaDoc;
15 import java.io.PrintStream JavaDoc;
16 import java.io.UnsupportedEncodingException JavaDoc;
17
18 /**
19  * BASE64 encoder implementation.
20  * Provides encoding methods, using the BASE64 encoding rules, as defined
21  * in the MIME specification, <a HREF="http://ietf.org/rfc/rfc1521.txt">rfc1521</a>.
22  *
23  *
24  * This class is a modified version based on code
25  * obtained from the w3 consortium website,
26  * which is subject to their generic copyright notice:
27  *
28  * <dl>
29  * <dd><a HREF="http://www.w3.org/Consortium/Legal/">Copyright</a> © [$date-of-software] <a
30  * HREF="http://www.w3.org/">World Wide Web Consortium</a>, (<a
31  * HREF="http://www.lcs.mit.edu/">Massachusetts Institute of Technology</a>, <a
32  * HREF="http://www.inria.fr/">Institut National de Recherche en Informatique et en
33  * Automatique</a>, <a HREF="http://www.keio.ac.jp/">Keio University</a>). All Rights
34  * Reserved. This program is distributed under the <a
35  * HREF="http://www.w3.org/Consortium/Legal/copyright-software-19980720.html">W3C's Software
36  * Intellectual Property License</a>. This program is distributed in the hope that it will be
37  * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
38  * FITNESS FOR A PARTICULAR PURPOSE. See W3C License <a
39  * HREF="http://www.w3.org/Consortium/Legal/">http://www.w3.org/Consortium/Legal/</a> for
40  * more details. </dd>
41  *</dl>
42  *
43  *
44  */

45 public final class Base64Encoder
46 {
47    private static final int BUFFER_SIZE = 1024 ;
48    private static final byte encoding[] =
49    {
50       (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D',
51       (byte) 'E', (byte) 'F', (byte) 'G', (byte) 'H', // 0-7
52
(byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L',
53       (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', // 8-15
54
(byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T',
55       (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', // 16-23
56
(byte) 'Y', (byte) 'Z', (byte) 'a', (byte) 'b',
57       (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', // 24-31
58
(byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j',
59       (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', // 32-39
60
(byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r',
61       (byte) 's', (byte) 't', (byte) 'u', (byte) 'v', // 40-47
62
(byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z',
63       (byte) '0', (byte) '1', (byte) '2', (byte) '3', // 48-55
64
(byte) '4', (byte) '5', (byte) '6', (byte) '7',
65       (byte) '8', (byte) '9', (byte) '+', (byte) '/', // 56-63
66
(byte) '=' // 64
67
};
68
69
70   /**
71    * Encodes data from supplied input to output.
72    * @param in The input stream to be encoded.
73    * @param out The output stream, to write encoded data to.
74    */

75    public static void encode(InputStream JavaDoc in, OutputStream JavaDoc out) throws IOException JavaDoc
76    {
77       process(in, out);
78    }
79
80   /**
81    * Encode the supplied byte array and write the encoded
82    * data to the OutputStream <i>out</i>.
83    */

84    public static void encode(byte input[], OutputStream JavaDoc out) throws IOException JavaDoc
85    {
86       ByteArrayInputStream JavaDoc in = new ByteArrayInputStream JavaDoc(input);
87       process(in, out);
88    }
89
90   /**
91    * Encode the given string,and return the encoded version as a string.
92    *
93    * @return A String, representing the encoded content of the input String.
94    */

95    public static String JavaDoc encode(String JavaDoc input) throws IOException JavaDoc
96    {
97        byte bytes[] ;
98       bytes = input.getBytes("ISO-8859-1");
99       return encode (bytes);
100    }
101
102   /**
103    * Encode the given byte array and return the result as a string.
104    */

105    public static String JavaDoc encode(byte bytes[]) throws IOException JavaDoc
106    {
107       ByteArrayInputStream JavaDoc in = new ByteArrayInputStream JavaDoc(bytes);
108       ByteArrayOutputStream JavaDoc out = new ByteArrayOutputStream JavaDoc();
109       process(in, out);
110       return out.toString("ISO-8859-1");
111    }
112
113   /**
114    * Run with one argument, prints the encoded version of it.
115    * With two, the second is assumed to be the name of a MessageDigest to
116    * be applied to the string before encoding (useful for generating
117    * password hashes).
118    * <p>
119    * Alternatively, use the openssl utility, for example:
120    * <p>
121    * echo -n "password" | openssl dgst -sha1 -binary | openssl base64
122    *
123    */

124    public static void main (String JavaDoc args[]) throws Exception JavaDoc
125    {
126       if(args.length == 1)
127       {
128          System.out.println ("["+ Base64Encoder.encode(args[0])+"]");
129       // joe:eoj -> am9lOmVvag==
130
// 12345678:87654321 -> MTIzNDU2Nzg6ODc2NTQzMjE=
131
}
132       else if (args.length == 2)
133       {
134          byte[] hash = java.security.MessageDigest.getInstance(args[1]).digest(args[0].getBytes());
135          System.out.println ("["+ Base64Encoder.encode(hash)+"]");
136       }
137       else
138       {
139          System.out.println("Usage: Base64Encoder <string> <optional hash algorithm>");
140       }
141    }
142
143 // Private ----------------------------------------------------------------
144

145    private static int get1(byte buf[], int off)
146    {
147       return (buf[off] & 0xfc) >> 2 ;
148    }
149
150    private static int get2(byte buf[], int off)
151    {
152       return ((buf[off]&0x3) << 4) | ((buf[off+1]&0xf0) >>> 4) ;
153    }
154
155    private static int get3(byte buf[], int off)
156    {
157       return ((buf[off+1] & 0x0f) << 2) | ((buf[off+2] & 0xc0) >>> 6) ;
158    }
159
160    private static int get4(byte buf[], int off)
161    {
162       return buf[off+2] & 0x3f ;
163    }
164
165   /**
166    * Process the data: encode the input stream to the output stream.
167    * This method runs through the input stream, encoding it to the output
168    * stream.
169    * @exception IOException If we weren't able to access the input stream or
170    * the output stream.
171    */

172    private static void process(InputStream JavaDoc in, OutputStream JavaDoc out) throws IOException JavaDoc
173    {
174       byte buffer[] = new byte[BUFFER_SIZE] ;
175       int got = -1 ;
176       int off = 0 ;
177       int count = 0 ;
178       while ((got = in.read(buffer, off, BUFFER_SIZE-off)) > 0)
179       {
180          if ( got >= 3 )
181          {
182             got += off;
183             off = 0;
184             while (off + 3 <= got)
185             {
186                 int c1 = get1(buffer,off);
187                 int c2 = get2(buffer,off);
188                 int c3 = get3(buffer,off);
189                 int c4 = get4(buffer,off);
190                 switch (count)
191                 {
192                     case 73:
193                        out.write(encoding[c1]);
194                        out.write(encoding[c2]);
195                        out.write(encoding[c3]);
196                        out.write ('\n') ;
197                        out.write(encoding[c4]);
198                        count = 1 ;
199                        break ;
200                      case 74:
201                        out.write(encoding[c1]);
202                        out.write(encoding[c2]);
203                        out.write ('\n') ;
204                        out.write(encoding[c3]);
205                        out.write(encoding[c4]) ;
206                        count = 2 ;
207                        break ;
208                      case 75:
209                        out.write(encoding[c1]);
210                        out.write ('\n') ;
211                        out.write(encoding[c2]);
212                        out.write(encoding[c3]);
213                        out.write(encoding[c4]) ;
214                        count = 3 ;
215                        break ;
216                      case 76:
217                        out.write('\n') ;
218                        out.write(encoding[c1]);
219                        out.write(encoding[c2]);
220                        out.write(encoding[c3]);
221                        out.write(encoding[c4]);
222                        count = 4;
223                        break;
224                      default:
225                        out.write(encoding[c1]);
226                        out.write(encoding[c2]);
227                        out.write(encoding[c3]);
228                        out.write(encoding[c4]);
229                        count += 4;
230                        break;
231                 }
232                 off += 3;
233             }
234             // Copy remaining bytes to beginning of buffer:
235
for ( int i = 0 ; i < 3 ;i++)
236                 buffer[i] = (i < got-off) ? buffer[off+i] : ((byte) 0);
237             off = got-off ;
238          }
239          else
240          {
241             // Total read amount is less then 3 bytes:
242
off += got;
243          }
244       }
245       // Manage the last bytes, from 0 to off:
246
switch (off) {
247         case 1:
248             out.write(encoding[get1(buffer, 0)]);
249             out.write(encoding[get2(buffer, 0)]);
250             out.write('=');
251             out.write('=');
252             break ;
253         case 2:
254             out.write(encoding[get1(buffer, 0)]);
255             out.write(encoding[get2(buffer, 0)]);
256             out.write(encoding[get3(buffer, 0)]);
257             out.write('=');
258       }
259       return;
260    }
261 }
262
263
Popular Tags