Skip to content

Commit 92d9940

Browse files
committed
improve: validate only first 3 bytes of JPEG signature to accept more valid files.
The 4th byte might be have different values and instead of maintaining all of the possible values, let's check only first 3 bytes.
1 parent 2561795 commit 92d9940

File tree

1 file changed

+4
-12
lines changed

1 file changed

+4
-12
lines changed

src/main/java/ru/mystamps/web/support/beanvalidation/ImageFileValidator.java

+4-12
Original file line numberDiff line numberDiff line change
@@ -36,10 +36,8 @@ public class ImageFileValidator implements ConstraintValidator<ImageFile, Multip
3636
private static final Logger LOG = LoggerFactory.getLogger(ImageFileValidator.class);
3737

3838
// see https://en.wikipedia.org/wiki/JPEG#Syntax_and_structure
39-
// CheckStyle: ignore NoWhitespaceAfterCheck for next 3 lines
40-
private static final byte[][] JPEG_SIGNATURES = {
41-
{ (byte)0xFF, (byte)0xD8, (byte)0xFF, (byte)0xE0 },
42-
{ (byte)0xFF, (byte)0xD8, (byte)0xFF, (byte)0xE1 }
39+
private static final byte[] JPEG_SIGNATURE = {
40+
(byte)0xFF, (byte)0xD8, (byte)0xFF,
4341
};
4442

4543
// see https://en.wikipedia.org/wiki/Portable_Network_Graphics#File_header
@@ -50,14 +48,8 @@ public class ImageFileValidator implements ConstraintValidator<ImageFile, Multip
5048
private static boolean isJpeg(byte[] bytes) {
5149
// FIXME: also check that last 2 bytes are FF D9 (use RandomAccessFile)
5250
// FIXME(java9): use Arrays.equals() with 6 parameters to avoid memory allocation
53-
byte[] firstBytes = Arrays.copyOf(bytes, JPEG_SIGNATURES[0].length);
54-
for (byte[] signature: JPEG_SIGNATURES) {
55-
if (Arrays.equals(firstBytes, signature)) {
56-
return true;
57-
}
58-
}
59-
60-
return false;
51+
byte[] firstBytes = Arrays.copyOf(bytes, JPEG_SIGNATURE.length);
52+
return Arrays.equals(firstBytes, JPEG_SIGNATURE);
6153
}
6254

6355
private static boolean isPng(byte[] bytes) {

0 commit comments

Comments
 (0)