1 /*****************************************************************
2 * Licensed to the Apache Software Foundation (ASF) under one *
3 * or more contributor license agreements. See the NOTICE file *
4 * distributed with this work for additional information *
5 * regarding copyright ownership. The ASF licenses this file *
6 * to you under the Apache License, Version 2.0 (the *
7 * "License"); you may not use this file except in compliance *
8 * with the License. You may obtain a copy of the License at *
9 * *
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 ****************************************************************/
19
20 package org.apache.james.util;
21
22 import javax.mail.internet.MimeUtility;
23 import java.io.BufferedReader;
24 import java.io.ByteArrayInputStream;
25 import java.io.ByteArrayOutputStream;
26 import java.io.InputStreamReader;
27
28
29 /***
30 * Simple Base64 string decoding function
31 *
32 * @version This is $Revision: 494012 $
33 */
34
35 public class Base64 {
36
37 public static BufferedReader decode(String b64string) throws Exception {
38 return new BufferedReader(
39 new InputStreamReader(
40 MimeUtility.decode(
41 new ByteArrayInputStream(
42 b64string.getBytes()), "base64")));
43 }
44
45 public static String decodeAsString(String b64string) throws Exception {
46 if (b64string == null) {
47 return b64string;
48 }
49 String returnString = decode(b64string).readLine();
50 if (returnString == null) {
51 return returnString;
52 }
53 return returnString.trim();
54 }
55
56 public static ByteArrayOutputStream encode(String plaintext)
57 throws Exception {
58 ByteArrayOutputStream out = new ByteArrayOutputStream();
59 byte[] in = plaintext.getBytes();
60 ByteArrayOutputStream inStream = new ByteArrayOutputStream();
61 inStream.write(in, 0, in.length);
62
63 if ((in.length % 3 ) == 1){
64 inStream.write(0);
65 inStream.write(0);
66 } else if((in.length % 3 ) == 2){
67 inStream.write(0);
68 }
69 inStream.writeTo( MimeUtility.encode(out, "base64") );
70 return out;
71 }
72
73 public static String encodeAsString(String plaintext) throws Exception {
74 return encode(plaintext).toString();
75 }
76
77
78 }