01: /*
02: * This file is part of PFIXCORE.
03: *
04: * PFIXCORE is free software; you can redistribute it and/or modify
05: * it under the terms of the GNU Lesser General Public License as published by
06: * the Free Software Foundation; either version 2 of the License, or
07: * (at your option) any later version.
08: *
09: * PFIXCORE is distributed in the hope that it will be useful,
10: * but WITHOUT ANY WARRANTY; without even the implied warranty of
11: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12: * GNU Lesser General Public License for more details.
13: *
14: * You should have received a copy of the GNU Lesser General Public License
15: * along with PFIXCORE; if not, write to the Free Software
16: * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17: */
18: package de.schlund.pfixxml.util;
19:
20: import java.io.ByteArrayInputStream;
21: import java.io.ByteArrayOutputStream;
22: import java.io.InputStream;
23: import java.io.OutputStream;
24:
25: import javax.mail.internet.MimeUtility;
26:
27: /**
28: * Helper class for decoding/encoding bytes using the Base64 algorithm.
29: * Therefore it uses javax.mail.internet.MimeUtility. The implementation doesn't
30: * perform as well as other specialized low-level implementations of the
31: * algorithm and shouldn't be used in performance critical scenarios.
32: *
33: * @author mleidig@schlund.de
34: *
35: */
36: public class Base64Utils {
37:
38: /**
39: * Encode bytes using the Base64 algorithm (the linebreak after 76 signs can
40: * be optionally removed).
41: */
42: public static String encode(byte[] bytes, boolean withNewLines) {
43: try {
44: ByteArrayOutputStream baos = new ByteArrayOutputStream();
45: OutputStream os = MimeUtility.encode(baos, "base64");
46: os.write(bytes);
47: os.close();
48: String str = new String(baos.toByteArray(), "utf8");
49: if (!withNewLines)
50: str = str.replaceAll("\r\n", "");
51: return str;
52: } catch (Exception x) {
53: throw new RuntimeException("Base64 encoding failed", x);
54: }
55: }
56:
57: /**
58: * Decode string representation of Base64 encoded bytes.
59: */
60: public static byte[] decode(String str) {
61: try {
62: byte[] bytes = str.getBytes("utf8");
63: ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
64: InputStream is = MimeUtility.decode(bais, "Base64");
65: byte[] tmp = new byte[bytes.length];
66: int n = is.read(tmp);
67: byte[] res = new byte[n];
68: System.arraycopy(tmp, 0, res, 0, n);
69: return res;
70: } catch (Exception x) {
71: throw new RuntimeException("Base64 decoding failed", x);
72: }
73: }
74:
75: public static void main(String[] args) throws Exception {
76: String url = "http://pustefix-framework.org";
77: System.out.println(url);
78: String enc = encode(url.getBytes("utf8"), false);
79: System.out.println(enc);
80: String dec = new String(decode(enc), "utf8");
81: System.out.println(dec);
82: System.out.println(dec.equals(url));
83: }
84:
85: }
|