01: /****************************************************************
02: * Licensed to the Apache Software Foundation (ASF) under one *
03: * or more contributor license agreements. See the NOTICE file *
04: * distributed with this work for additional information *
05: * regarding copyright ownership. The ASF licenses this file *
06: * to you under the Apache License, Version 2.0 (the *
07: * "License"); you may not use this file except in compliance *
08: * with the License. You may obtain a copy of the License at *
09: * *
10: * http://www.apache.org/licenses/LICENSE-2.0 *
11: * *
12: * Unless required by applicable law or agreed to in writing, *
13: * software distributed under the License is distributed on an *
14: * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
15: * KIND, either express or implied. See the License for the *
16: * specific language governing permissions and limitations *
17: * under the License. *
18: ****************************************************************/package org.apache.james.util;
19:
20: import javax.mail.internet.MimeUtility;
21: import java.io.BufferedReader;
22: import java.io.ByteArrayInputStream;
23: import java.io.ByteArrayOutputStream;
24: import java.io.InputStreamReader;
25:
26: /**
27: * Simple Base64 string decoding function
28: *
29: * @version This is $Revision: 494012 $
30: */
31:
32: public class Base64 {
33:
34: public static BufferedReader decode(String b64string)
35: throws Exception {
36: return new BufferedReader(new InputStreamReader(MimeUtility
37: .decode(new ByteArrayInputStream(b64string.getBytes()),
38: "base64")));
39: }
40:
41: public static String decodeAsString(String b64string)
42: throws Exception {
43: if (b64string == null) {
44: return b64string;
45: }
46: String returnString = decode(b64string).readLine();
47: if (returnString == null) {
48: return returnString;
49: }
50: return returnString.trim();
51: }
52:
53: public static ByteArrayOutputStream encode(String plaintext)
54: throws Exception {
55: ByteArrayOutputStream out = new ByteArrayOutputStream();
56: byte[] in = plaintext.getBytes();
57: ByteArrayOutputStream inStream = new ByteArrayOutputStream();
58: inStream.write(in, 0, in.length);
59: // pad
60: if ((in.length % 3) == 1) {
61: inStream.write(0);
62: inStream.write(0);
63: } else if ((in.length % 3) == 2) {
64: inStream.write(0);
65: }
66: inStream.writeTo(MimeUtility.encode(out, "base64"));
67: return out;
68: }
69:
70: public static String encodeAsString(String plaintext)
71: throws Exception {
72: return encode(plaintext).toString();
73: }
74:
75: }
|