public class CustomBase64 {
private static final char[] BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
.toCharArray();
public static String encode(byte[] data) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < data.length; i += 3) {
int firstByte = data[i] & 0xFF;
int secondByte = i + 1 < data.length ? data[i + 1] & 0xFF : 0;
int thirdByte = i + 2 < data.length ? data[i + 2] & 0xFF : 0;
result.append(BASE64_CHARS[firstByte >>> 2]);
result.append(i + 2 < data.length ? BASE64_CHARS[thirdByte & 0x3F] : '=');
}
return result.toString();
}
public static byte[] decode(String data) {
ByteArrayOutputStream result = new ByteArrayOutputStream();
for (int i = 0; i < data.length(); i += 4) {
int firstChar = indexOf(BASE64_CHARS, data.charAt(i));
int secondChar = indexOf(BASE64_CHARS, data.charAt(i + 1));
int thirdChar = indexOf(BASE64_CHARS, data.charAt(i + 2));
int fourthChar = indexOf(BASE64_CHARS, data.charAt(i + 3));
result.write(firstByte);
if (thirdChar != 64) { // ASCII value of '=' is 64
result.write(secondByte);
}
if (fourthChar != 64) {
result.write(thirdByte);
}
}
return result.toByteArray();
}
private static int indexOf(char[] array, char target) {
for (int i = 0; i < array.length; i++) {
if (array[i] == target) {
return i;
}
}
throw new IllegalArgumentException("Invalid character: " + target);
}
}
public class Main {
public static void main(String[] args) {
String originalString = "Hello, World!";
byte[] encoded = CustomBase64.encode(originalString.getBytes());
byte[] decoded = CustomBase64.decode(new String(encoded));
System.out.println("Original: " + originalString);
System.out.println("Encoded: " + new String(encoded));
System.out.println("Decoded: " + new String(decoded));
}
}