1/*2 * Copyright 2000-2001,2004 The Apache Software Foundation.3 * 4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 * 8 * http://www.apache.org/licenses/LICENSE-2.09 * 10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */16packageorg.apache.jetspeed.util;
1718import javax.mail.internet.MimeUtility;
19import java.io.ByteArrayInputStream;
20import java.io.ByteArrayOutputStream;
21import java.io.InputStream;
2223/***24 * Simple Base64 string decoding function25 * @author Jason Borden <jborden@javasense.com>26 *27 * This class was copied from the jakarta-james project.28 * The only change made, besides comments, is the package name.29 * This class orgininated in org.apache.james.util as version 1.330 * which was committed by darrel on 2002/01/18 02:48:3931 * 32 * $Id: Base64.java,v 1.5 2004/02/23 03:23:42 jford Exp $33 * Committed on $Date: 2004/02/23 03:23:42 $ by: $Name: $ 34 */3536publicclass Base64 {
3738publicstatic String decodeAsString(String b64string) throws Exception
39 {
40returnnew String(decodeAsByteArray(b64string));
41 }
4243publicstatic byte[] decodeAsByteArray(String b64string) throws Exception
44 {
45 InputStream in = MimeUtility.decode(new ByteArrayInputStream(
46 b64string.getBytes()), "base64");
4748 ByteArrayOutputStream out = new ByteArrayOutputStream();
4950while(true)
51 {
52int b = in.read();
53if (b == -1) break;
54else out.write(b);
55 }
5657return out.toByteArray();
58 }
5960publicstatic String encodeAsString(String plaintext) throws Exception
61 {
62return encodeAsString(plaintext.getBytes());
63 }
6465publicstatic String encodeAsString(byte[] plaindata) throws Exception
66 {
67 ByteArrayOutputStream out = new ByteArrayOutputStream();
68 ByteArrayOutputStream inStream = new ByteArrayOutputStream();
6970 inStream.write(plaindata, 0, plaindata.length);
7172// pad73if ((plaindata.length % 3 ) == 1)
74 {
75 inStream.write(0);
76 inStream.write(0);
77 }
78elseif((plaindata.length % 3 ) == 2)
79 {
80 inStream.write(0);
81 }
8283 inStream.writeTo(MimeUtility.encode(out, "base64"));
84return out.toString();
85 }
8687 }
88