public class Base64Utils {
private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
public static String base64(String str) {
return base64(str == null ? null : str.getBytes());
}
public static String base64(byte[] bytes) {
if (bytes == null || bytes.length == 0) {
return "";
}
int length = bytes.length;
int gSize = 3;
int group = (length - 1) / gSize + 1;
int[] arr = new int[4];
byte[] result = new byte[group * 4];
int n = 0;
while (n < group) {
int m = 0;
int words = arr.length;
int offset = n * gSize;
for (int i = 0; i < gSize; i++) {
int index = offset + i;
if (index < length) {
m = (m << 8) + bytes[index];
} else {
if (i == 1) {
m = m << 4;
words = 2;
} else {
m = m << 2;
words = 3;
}
break;
}
}
int r = n << 2;
for (int i = 4; i > 0; i--) {
if (i <= words) {
result[r + i - 1] = (byte) CHARACTERS.charAt(m & 0x3f);
m = m >> 6;
} else {
result[r + i - 1] = (byte) '=';
}
}
n++;
}
return new String(result);
}
}