01: package org.bouncycastle.util.encoders;
02:
03: import java.io.ByteArrayOutputStream;
04: import java.io.IOException;
05: import java.io.OutputStream;
06:
07: public class Base64 {
08: private static final Encoder encoder = new Base64Encoder();
09:
10: /**
11: * encode the input data producing a base 64 encoded byte array.
12: *
13: * @return a byte array containing the base 64 encoded data.
14: */
15: public static byte[] encode(byte[] data) {
16: int len = (data.length + 2) / 3 * 4;
17: ByteArrayOutputStream bOut = new ByteArrayOutputStream(len);
18:
19: try {
20: encoder.encode(data, 0, data.length, bOut);
21: } catch (IOException e) {
22: throw new RuntimeException(
23: "exception encoding base64 string: " + e);
24: }
25:
26: return bOut.toByteArray();
27: }
28:
29: /**
30: * Encode the byte data to base 64 writing it to the given output stream.
31: *
32: * @return the number of bytes produced.
33: */
34: public static int encode(byte[] data, OutputStream out)
35: throws IOException {
36: return encoder.encode(data, 0, data.length, out);
37: }
38:
39: /**
40: * Encode the byte data to base 64 writing it to the given output stream.
41: *
42: * @return the number of bytes produced.
43: */
44: public static int encode(byte[] data, int off, int length,
45: OutputStream out) throws IOException {
46: return encoder.encode(data, off, length, out);
47: }
48:
49: /**
50: * decode the base 64 encoded input data. It is assumed the input data is valid.
51: *
52: * @return a byte array representing the decoded data.
53: */
54: public static byte[] decode(byte[] data) {
55: int len = data.length / 4 * 3;
56: ByteArrayOutputStream bOut = new ByteArrayOutputStream(len);
57:
58: try {
59: encoder.decode(data, 0, data.length, bOut);
60: } catch (IOException e) {
61: throw new RuntimeException(
62: "exception decoding base64 string: " + e);
63: }
64:
65: return bOut.toByteArray();
66: }
67:
68: /**
69: * decode the base 64 encoded String data - whitespace will be ignored.
70: *
71: * @return a byte array representing the decoded data.
72: */
73: public static byte[] decode(String data) {
74: int len = data.length() / 4 * 3;
75: ByteArrayOutputStream bOut = new ByteArrayOutputStream(len);
76:
77: try {
78: encoder.decode(data, bOut);
79: } catch (IOException e) {
80: throw new RuntimeException(
81: "exception decoding base64 string: " + e);
82: }
83:
84: return bOut.toByteArray();
85: }
86:
87: /**
88: * decode the base 64 encoded String data writing it to the given output stream,
89: * whitespace characters will be ignored.
90: *
91: * @return the number of bytes produced.
92: */
93: public static int decode(String data, OutputStream out)
94: throws IOException {
95: return encoder.decode(data, out);
96: }
97: }
|