Base16Codec implements Codec { @Override public byte[] decode(byte[] src, final int length) { if (length % 2 != 0) { throw new IllegalArgumentException( "Input is expected to be encoded in multiple of 2 bytes but found: " + length ); } final byte[] dest = new byte[length / 2]; for (int i=0, j=0; j < dest.length; j++) { dest[j] = (byte) ( pos(src[i++]) << 4 | pos(src[i++]) ) ; } return dest; } Base16Codec();   Base16Codec(boolean upperCase); @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 = { "", "66", "666F", "666F6F", "666F6F62", "666F6F6261", "666F6F626172", }; for (int i=0; i < testVectors.length; i++) { String data = testVectors[i]; byte[] source = data.getBytes("UTF-8"); String b16encoded = Base16.encodeAsString(data.getBytes("UTF-8")); Assert.assertEquals(expected[i], b16encoded); byte[] b16 = b16encoded.getBytes("UTF-8"); byte[] decoded = Base16.decode(b16); Assert.assertTrue(Arrays.equals(source, decoded)); decoded = Base16Lower.decode(b16); 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 b16Encoded = Base16.encodeAsString(digest); { decoded = Base16.decode(b16Encoded); Assert.assertTrue(Arrays.equals(decoded, digest)); decoded = Base16Lower.decode(b16Encoded); Assert.assertTrue(Arrays.equals(decoded, digest)); } { decoded = Base16.decode(b16Encoded.toLowerCase()); Assert.assertTrue(Arrays.equals(decoded, digest)); decoded = Base16Lower.decode(b16Encoded.toLowerCase()); Assert.assertTrue(Arrays.equals(decoded, digest)); } } }