1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.apache.jetspeed.util;
17
18 import javax.mail.internet.MimeUtility;
19 import java.io.ByteArrayInputStream;
20 import java.io.ByteArrayOutputStream;
21 import java.io.InputStream;
22
23 /***
24 * Simple Base64 string decoding function
25 * @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.3
30 * which was committed by darrel on 2002/01/18 02:48:39
31 *
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 */
35
36 public class Base64 {
37
38 public static String decodeAsString(String b64string) throws Exception
39 {
40 return new String(decodeAsByteArray(b64string));
41 }
42
43 public static byte[] decodeAsByteArray(String b64string) throws Exception
44 {
45 InputStream in = MimeUtility.decode(new ByteArrayInputStream(
46 b64string.getBytes()), "base64");
47
48 ByteArrayOutputStream out = new ByteArrayOutputStream();
49
50 while(true)
51 {
52 int b = in.read();
53 if (b == -1) break;
54 else out.write(b);
55 }
56
57 return out.toByteArray();
58 }
59
60 public static String encodeAsString(String plaintext) throws Exception
61 {
62 return encodeAsString(plaintext.getBytes());
63 }
64
65 public static String encodeAsString(byte[] plaindata) throws Exception
66 {
67 ByteArrayOutputStream out = new ByteArrayOutputStream();
68 ByteArrayOutputStream inStream = new ByteArrayOutputStream();
69
70 inStream.write(plaindata, 0, plaindata.length);
71
72
73 if ((plaindata.length % 3 ) == 1)
74 {
75 inStream.write(0);
76 inStream.write(0);
77 }
78 else if((plaindata.length % 3 ) == 2)
79 {
80 inStream.write(0);
81 }
82
83 inStream.writeTo(MimeUtility.encode(out, "base64"));
84 return out.toString();
85 }
86
87 }
88