Base64 { @SuppressWarnings("fallthrough") public static byte[] decode(final byte[] buffer) { if (buffer.length < 4 && (buffer.length % 4) != 0) { return new byte[0]; } final int ccount = buffer.length / 4; final int paddingCount = (buffer[buffer.length - 1] == '=' ? 1 : 0) + (buffer[buffer.length - 2] == '=' ? 1 : 0); final byte[] result = new byte[3 * (ccount - 1) + (3 - paddingCount)]; for (int i = 0; i < (ccount - 1); i++) { result[i * 3] = (byte) ((BASE64INDEXES[buffer[i * 4]] << 2) | (BASE64INDEXES[buffer[i * 4 + 1]] >> 4)); result[i * 3 + 1] = (byte) ((BASE64INDEXES[buffer[i * 4 + 1]] << 4) | (BASE64INDEXES[buffer[i * 4 + 2]] >> 2)); result[i * 3 + 2] = (byte) ((BASE64INDEXES[buffer[i * 4 + 2]] << 6) | BASE64INDEXES[buffer[i * 4 + 3]]); } final int i = ccount - 1; switch (paddingCount) { case 0: result[i * 3 + 2] = (byte) ((BASE64INDEXES[buffer[i * 4 + 2]] << 6) | BASE64INDEXES[buffer[i * 4 + 3]]); result[i * 3 + 1] = (byte) ((BASE64INDEXES[buffer[i * 4 + 1]] << 4) | (BASE64INDEXES[buffer[i * 4 + 2]] >> 2)); result[i * 3] = (byte) ((BASE64INDEXES[buffer[i * 4]] << 2) | (BASE64INDEXES[buffer[i * 4 + 1]] >> 4)); break; case 1: result[i * 3 + 1] = (byte) ((BASE64INDEXES[buffer[i * 4 + 1]] << 4) | (BASE64INDEXES[buffer[i * 4 + 2]] >> 2)); result[i * 3] = (byte) ((BASE64INDEXES[buffer[i * 4]] << 2) | (BASE64INDEXES[buffer[i * 4 + 1]] >> 4)); break; case 2: result[i * 3] = (byte) ((BASE64INDEXES[buffer[i * 4]] << 2) | (BASE64INDEXES[buffer[i * 4 + 1]] >> 4)); break; } return result; }  static byte[] encode(final byte[] buffer); @SuppressWarnings("fallthrough") static byte[] decode(final byte[] buffer); static String encodeAsString(final byte[] buffer); static String encodeAsString(final String text); static String decodeAsString(final byte[] buffer); static String decodeAsString(final String text);  }
@Test public void testDecodeString() throws Exception { for (int i = 0; i < encoded.length; i++) { assertEquals(decoded[i], new String(Base64.decode(encoded[i].getBytes("ASCII")), "ASCII")); } }
@Test public void testDecodeString2() { String data = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0" + "+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn" + "+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6" + "/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/w=="; byte[] result = Base64.decode(data.getBytes()); assertEquals("incorrect length", result.length, 256); for (int i = 0; i < 256; ++i) { assertEquals("incorrect value", result[i], (byte) i); } }