Base64 { public static byte[] encode(final byte[] buffer) { final int ccount = buffer.length / 3; final int rest = buffer.length % 3; final byte[] result = new byte[(ccount + (rest > 0 ? 1 : 0)) * 4]; for (int i = 0; i < ccount; i++) { result[i * 4] = CHAR_SET[(buffer[i * 3] >> 2) & 0xff]; result[i * 4 + 1] = CHAR_SET[(((buffer[i * 3] & 0x03) << 4) | (buffer[i * 3 + 1] >> 4)) & 0xff]; result[i * 4 + 2] = CHAR_SET[(((buffer[i * 3 + 1] & 0x0f) << 2) | (buffer[i * 3 + 2] >> 6)) & 0xff]; result[i * 4 + 3] = CHAR_SET[buffer[i * 3 + 2] & 0x3f]; } int temp = 0; if (rest > 0) { if (rest == 2) { result[ccount * 4 + 2] = CHAR_SET[((buffer[ccount * 3 + 1] & 0x0f) << 2) & 0xff]; temp = buffer[ccount * 3 + 1] >> 4; } else { result[ccount * 4 + 2] = CHAR_SET[CHAR_SET.length - 1]; } result[ccount * 4 + 3] = CHAR_SET[CHAR_SET.length - 1]; result[ccount * 4 + 1] = CHAR_SET[(((buffer[ccount * 3] & 0x03) << 4) | temp) & 0xff]; result[ccount * 4] = CHAR_SET[(buffer[ccount * 3] >> 2) & 0xff]; } 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 testEncodeString() throws Exception { for (int i = 0; i < decoded.length; i++) { assertEquals(encoded[i], new String(Base64.encode(decoded[i].getBytes("ASCII")), "ASCII")); } }
@Test public void testEncodeByteArray() { byte[] data = new byte[256]; for (int i = 0; i < 256; ++i) { data[i] = (byte) (255 - i); } try { new String(Base64.encode(data)); fail(); } catch (Exception e) { } }