diff --git a/core/src/main/java/org/eclipse/angus/mail/util/BASE64DecoderStream.java b/core/src/main/java/org/eclipse/angus/mail/util/BASE64DecoderStream.java index 52478c9e..af64bc36 100644 --- a/core/src/main/java/org/eclipse/angus/mail/util/BASE64DecoderStream.java +++ b/core/src/main/java/org/eclipse/angus/mail/util/BASE64DecoderStream.java @@ -202,7 +202,7 @@ public int available() throws IOException { private final static byte[] pem_convert_array = new byte[256]; static { - for (int i = 0; i < 255; i++) + for (int i = 0; i < pem_convert_array.length; i++) pem_convert_array[i] = -1; for (int i = 0; i < pem_array.length; i++) pem_convert_array[pem_array[i]] = (byte) i; diff --git a/providers/angus-mail/src/test/java/org/eclipse/angus/mail/util/BASE64Test.java b/providers/angus-mail/src/test/java/org/eclipse/angus/mail/util/BASE64Test.java index eee00b7f..e0020fea 100644 --- a/providers/angus-mail/src/test/java/org/eclipse/angus/mail/util/BASE64Test.java +++ b/providers/angus-mail/src/test/java/org/eclipse/angus/mail/util/BASE64Test.java @@ -278,6 +278,37 @@ public void testReadZeroBytes() throws Exception { //assertArrayEquals(decoded, result); } + /** + * A byte that is not part of the base64 alphabet must be skipped, + * the same way whitespace is. The 0xFF byte in particular must not + * be treated as a valid character. + */ + @Test + public void testNonBase64ByteSkipped() throws IOException { + // "TWFu" is the base64 encoding of "Man"; inject a stray 0xFF byte + byte[] clean = new byte[]{'T', 'W', 'F', 'u'}; + byte[] withStray = new byte[]{'T', 'W', (byte) 0xFF, 'F', 'u'}; + + byte[] expected = readFully(new BASE64DecoderStream( + new ByteArrayInputStream(clean))); + byte[] actual = readFully(new BASE64DecoderStream( + new ByteArrayInputStream(withStray))); + + Assert.assertArrayEquals("0xFF must be ignored like whitespace", + expected, actual); + // cross-check against a conformant decoder that ignores non-alphabet bytes + Assert.assertArrayEquals("must match JDK MIME decoder", + Base64.getMimeDecoder().decode(withStray), actual); + } + + private static byte[] readFully(InputStream in) throws IOException { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + int b; + while ((b = in.read()) != -1) + bos.write(b); + return bos.toByteArray(); + } + /** * Fill the buffer from the stream. */