import java.util.Arrays; public class Base64Test { private static char[] nrToChar; private static int[] charToNr; static { nrToChar = new char[64]; for (char i = 'A'; i <= 'Z'; i++) { nrToChar[i - 'A'] = i; } int offset = 'Z' - 'A' + 1; // 26 for (char i = 'a'; i <= 'z'; i++) { nrToChar[offset + (i - 'a')] = i; } offset = offset + 'z' - 'a' + 1; // 52 for (char i = '0'; i <= '9'; i++) { nrToChar[offset + (i - '0')] = i; } nrToChar[62] = '+'; nrToChar[63] = '/'; charToNr = new int[256]; for (int i = 0; i < 64; i++) { char c = nrToChar[i]; charToNr[c] = findNr(c); } } private static byte findNr(char c) { for (int i = 0; i < nrToChar.length; i++) { if (nrToChar[i] == c) { return (byte) i; } } throw new Error("Char not found"); } /** * requires: - input is a Base64 encoding. * ensurse: - result is the decoded data from the input. **/ public static byte[] base64Decode(String in) { int len = (in.length() / 4) * 3; byte[] out = new byte[len]; int j = 0; for (int i = 0; i < out.length; i += 3) { int a = charToNr[(int) in.charAt(j)]; int b = charToNr[(int) in.charAt(j + 1)]; int c = charToNr[(int) in.charAt(j + 2)]; int d = charToNr[(int) in.charAt(j + 3)]; out[i] = (byte) ((a << 2) | (b >> 4)); out[i + 1] = (byte) ((b << 4) | (c >> 2)); out[i + 2] = (byte) ((c << 6) | d); j += 4; } return out; } public static int unsignedByte2Int(byte a) { return (int) a & 0xFF; } /*** * requires: - input divisible by 3 (in.length % 3 == 0) * ensures: - result is a Base64 encoding of the input. * - input is not modified **/ public static String base64Encode(byte[] in) { int resLength = (in.length / 3) * 4; StringBuffer out = new StringBuffer(resLength); for (int i = 0; i < in.length; i += 3) { out.append(nrToChar[(in[i] >> 2) & 63]); out.append(nrToChar[((in[i] & 3) << 4) | ((in[i + 1] >> 4) & 15)]); out.append(nrToChar[((in[i + 1] & 15) << 2) | ((in[i + 2] >> 6) & 3)]); out.append(nrToChar[in[i + 2] & 63]); } return out.toString(); } public static void printByteArray(byte[] in) { for (int i = 0; i < in.length; i++) { System.out.print(in[i]); } } public static byte[] generate() { // TODO generate a random byte array. Note any input requirements to the // Base 64 function. return null; } public static boolean test(byte[] input) { try { // TODO Write a test for the Base64 encoder / decoder. return false; } catch (Exception e) { e.printStackTrace(); return false; } } public static void main(String[] args) { for (int i = 0; i < 10000; i++) { byte[] array = generate(); if (!test(array)) { System.out.println("Failed: " + Arrays.toString(array)); System.exit(0); } } System.out.println("Done."); } }