Base64Encodingpublic class Base64Encoding extends Object Converter to and from Base64 encoding. Base64 encoding is defined in
RFC 2045. |
Fields Summary |
---|
private static char[] | BASE64_CHARSConstants for conversion of binary data to Base64. From RFC 2045. | private static byte[] | BASE64_BYTESConstants for conversion of Base64 data to binary. The inverse
of the above table. |
Methods Summary |
---|
public static byte[] | fromBase64(java.lang.String sdata)Converts a BASE64 string to a byte array.
if (sdata == null || sdata.length() < 2) {
return new byte[0];
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
// copy the string to an array, and pad the end of the data with
// '=' characters.
int length = sdata.length();
char[] data = new char[length + 2];
sdata.getChars(0, length, data, 0);
data[length] = '=";
data[length + 1] = '=";
for (int i = nextCharIndex(data, 0); i < data.length; ) {
int char0 = data[i = nextCharIndex(data, i)];
if (char0 == '=") {
break;
}
int char1 = data[i = nextCharIndex(data, i + 1)];
if (char1 == '=") {
// stop here. this is not a valid Base64 fragment
break;
}
int char2 = data[i = nextCharIndex(data, i + 1)];
int char3 = data[i = nextCharIndex(data, i + 1)];
i = nextCharIndex(data, i + 1);
out.write(BASE64_BYTES[char0] << 2 | BASE64_BYTES[char1] >> 4);
if (char2 == '=") {
// only one byte
} else {
int value = BASE64_BYTES[char1] << 4 | BASE64_BYTES[char2] >> 2;
out.write(value & 0xff);
if (char3 == '=") {
// only 2 bytes
} else {
value = BASE64_BYTES[char2] << 6 | BASE64_BYTES[char3];
out.write(value & 0xff);
}
}
}
return out.toByteArray();
| private static int | nextCharIndex(char[] data, int i)Gets the index of the first character in the given array that
contains valid Base64 data. Starts searching from the given
index "i".
while (i < data.length &&
(data[i] > 0x7f || BASE64_BYTES[data[i]] == -1)) {
i ++;
}
return i;
| public static java.lang.String | toBase64(byte[] data, int lineLength, int indent)Converts a byte array to a BASE64 string.
StringBuffer sb = new StringBuffer();
for (int i = 0, charsInLine = 0; i < data.length; ) {
int byte0 = ((int) data[i++]) & 0xff;
int byte1 = (i < data.length) ? ((int) data[i++]) & 0xff : 0x100;
int byte2 = (i < data.length) ? ((int) data[i++]) & 0xff : 0x100;
sb.append(BASE64_CHARS[ byte0 >> 2 ]);
if (byte1 == 0x100) {
sb.append(BASE64_CHARS[ (byte0 << 4) & 0x30]);
sb.append("==");
} else {
sb.append(BASE64_CHARS[ (byte0 << 4 | byte1 >> 4) & 0x3f]);
if (byte2 == 0x100) {
sb.append(BASE64_CHARS[ (byte1 << 2) & 0x3f]);
sb.append('=");
} else {
sb.append(BASE64_CHARS[ (byte1 << 2 | byte2 >> 6) & 0x3f]);
sb.append(BASE64_CHARS[ byte2 & 0x3f ]);
}
}
charsInLine += 4;
if (charsInLine + 4 > lineLength && i < data.length) {
sb.append("\r\n");
for (int j = 0; j < indent; j++) {
sb.append(' ");
}
}
}
return sb.toString();
|
|