1
// Copyright (c) 1999-2004 Brian Wellington (bwelling@xbill.org)
3
package org.xbill.DNS.utils;
8
* Routines for converting between Strings of base64-encoded data and arrays of
11
* @author Brian Wellington
16
private static final String Base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
22
* Convert binary data to a base64-encoded String
23
* @param b An array containing binary data
24
* @return A String containing the encoded data
28
ByteArrayOutputStream os = new ByteArrayOutputStream();
30
for (int i = 0; i < (b.length + 2) / 3; i++) {
31
short [] s = new short[3];
32
short [] t = new short[4];
33
for (int j = 0; j < 3; j++) {
34
if ((i * 3 + j) < b.length)
35
s[j] = (short) (b[i*3+j] & 0xFF);
40
t[0] = (short) (s[0] >> 2);
42
t[1] = (short) (((s[0] & 0x3) << 4));
44
t[1] = (short) (((s[0] & 0x3) << 4) + (s[1] >> 4));
47
else if (s[2] == -1) {
48
t[2] = (short) (((s[1] & 0xF) << 2));
52
t[2] = (short) (((s[1] & 0xF) << 2) + (s[2] >> 6));
53
t[3] = (short) (s[2] & 0x3F);
55
for (int j = 0; j < 4; j++)
56
os.write(Base64.charAt(t[j]));
58
return new String(os.toByteArray());
62
* Formats data into a nicely formatted base64 encoded String
63
* @param b An array containing binary data
64
* @param lineLength The number of characters per line
65
* @param prefix A string prefixing the characters on each line
66
* @param addClose Whether to add a close parenthesis or not
67
* @return A String representing the formatted output
70
formatString(byte [] b, int lineLength, String prefix, boolean addClose) {
71
String s = toString(b);
72
StringBuffer sb = new StringBuffer();
73
for (int i = 0; i < s.length(); i += lineLength) {
75
if (i + lineLength >= s.length()) {
76
sb.append(s.substring(i));
81
sb.append(s.substring(i, i + lineLength));
90
* Convert a base64-encoded String to binary data
91
* @param str A String containing the encoded data
92
* @return An array containing the binary data, or null if the string is invalid
95
fromString(String str) {
96
ByteArrayOutputStream bs = new ByteArrayOutputStream();
97
byte [] raw = str.getBytes();
98
for (int i = 0; i < raw.length; i++) {
99
if (!Character.isWhitespace((char)raw[i]))
102
byte [] in = bs.toByteArray();
103
if (in.length % 4 != 0) {
108
DataOutputStream ds = new DataOutputStream(bs);
110
for (int i = 0; i < (in.length + 3) / 4; i++) {
111
short [] s = new short[4];
112
short [] t = new short[3];
114
for (int j = 0; j < 4; j++)
115
s[j] = (short) Base64.indexOf(in[i*4+j]);
117
t[0] = (short) ((s[0] << 2) + (s[1] >> 4));
119
t[1] = t[2] = (short) (-1);
120
if ((s[1] & 0xF) != 0)
123
else if (s[3] == 64) {
124
t[1] = (short) (((s[1] << 4) + (s[2] >> 2)) & 0xFF);
126
if ((s[2] & 0x3) != 0)
130
t[1] = (short) (((s[1] << 4) + (s[2] >> 2)) & 0xFF);
131
t[2] = (short) (((s[2] << 6) + s[3]) & 0xFF);
135
for (int j = 0; j < 3; j++)
139
catch (IOException e) {
142
return bs.toByteArray();