Base64Codec implements Codec { @Override public byte[] decode(byte[] src, final int length) { if (length % 4 != 0) throw new IllegalArgumentException ("Input is expected to be encoded in multiple of 4 bytes but found: " + length); int pads=0; int last = length-1; for (; pads < 2 && last > -1; last--, pads++) { if (src[last] != PAD) break; } final int fq; switch(pads) { case 0: fq=3; break; case 1: fq=2; break; case 2: fq=1; break; default: throw new Error("Impossible"); } final byte[] dest = new byte[length / 4 * 3 - (3-fq)]; int s=0, d=0; for (; d < dest.length - fq%3; s+=4,d+=3) decode4bytes(src, s, dest, d); if (fq < 3) decode1to3bytes(fq, src, s, dest, d); return dest; } Base64Codec(); protected  Base64Codec(byte[] alphabets); @Override byte[] encode(byte[] src); @Override byte[] decode(byte[] src, final int length);  }
@Test public void testVectorsPerRfc4648() throws NoSuchAlgorithmException, UnsupportedEncodingException { String[] testVectors = { "", "f", "fo", "foo", "foob", "fooba", "foobar", }; String[] expected = { "", "Zg==", "Zm8=", "Zm9v", "Zm9vYg==", "Zm9vYmE=", "Zm9vYmFy", }; for (int i=0; i < testVectors.length; i++) { String data = testVectors[i]; byte[] source = data.getBytes("UTF-8"); String b64encoded = Base64.encodeAsString(data.getBytes("UTF-8")); Assert.assertEquals(expected[i], b64encoded); byte[] b64 = b64encoded.getBytes("UTF-8"); byte[] decoded = Base64.decode(b64); Assert.assertTrue(Arrays.equals(source, decoded)); } }
@Test public void testCodecConsistency() throws NoSuchAlgorithmException, UnsupportedEncodingException { byte[] decoded = null; for (int h=0; h < 1000; h++) { byte[] digest = MessageDigest.getInstance("SHA-1").digest(UUID.randomUUID().toString().getBytes("UTF-8")); String b64Encoded = Base64.encodeAsString(digest); decoded = Base64.decode(b64Encoded); Assert.assertTrue(Arrays.equals(decoded, digest)); } }
@Test public void testImpossibleCases() { final String[] BASE64_IMPOSSIBLE_CASES = { "ZE==", "ZmC=", "Zm9vYE==", "Zm9vYmC=", }; for (String s: BASE64_IMPOSSIBLE_CASES) { try { Base64.decode(s); Assert.fail(); } catch(IllegalArgumentException ex) { } } }