ZipUtil { static long computeCrcOfCentralDir(RandomAccessFile raf, CentralDirectory dir) throws IOException { CRC32 crc = new CRC32(); long stillToRead = dir.size; raf.seek(dir.offset); int length = (int) Math.min(BUFFER_SIZE, stillToRead); byte[] buffer = new byte[BUFFER_SIZE]; length = raf.read(buffer, 0, length); while (length != -1) { crc.update(buffer, 0, length); stillToRead -= length; if (stillToRead == 0) { break; } length = (int) Math.min(BUFFER_SIZE, stillToRead); length = raf.read(buffer, 0, length); } return crc.getValue(); }    }
@Test public void testCrcValue() throws IOException { ZipFile zip = new ZipFile(zipFile); Enumeration<? extends ZipEntry> ref = zip.entries(); byte[] buffer = new byte[0x2000]; while (ref.hasMoreElements()) { ZipEntry refEntry = ref.nextElement(); if (refEntry.getSize() > 0) { File tmp = File.createTempFile("ZipUtilTest", ".fakezip"); InputStream in = zip.getInputStream(refEntry); OutputStream out = new FileOutputStream(tmp); int read = in.read(buffer); while (read != -1) { out.write(buffer, 0, read); read = in.read(buffer); } in.close(); out.close(); RandomAccessFile raf = new RandomAccessFile(tmp, "r"); CentralDirectory dir = new CentralDirectory(); dir.offset = 0; dir.size = raf.length(); long crc = ZipUtil.computeCrcOfCentralDir(raf, dir); Assert.assertEquals(refEntry.getCrc(), crc); raf.close(); tmp.delete(); } } zip.close(); }
@Test public void testInvalidCrcValue() throws IOException { ZipFile zip = new ZipFile(zipFile); Enumeration<? extends ZipEntry> ref = zip.entries(); byte[] buffer = new byte[0x2000]; while (ref.hasMoreElements()) { ZipEntry refEntry = ref.nextElement(); if (refEntry.getSize() > 0) { File tmp = File.createTempFile("ZipUtilTest", ".fakezip"); InputStream in = zip.getInputStream(refEntry); OutputStream out = new FileOutputStream(tmp); int read = in.read(buffer); while (read != -1) { out.write(buffer, 0, read); read = in.read(buffer); } in.close(); out.close(); RandomAccessFile raf = new RandomAccessFile(tmp, "r"); CentralDirectory dir = new CentralDirectory(); dir.offset = 0; dir.size = raf.length() - 1; long crc = ZipUtil.computeCrcOfCentralDir(raf, dir); Assert.assertNotEquals(refEntry.getCrc(), crc); raf.close(); tmp.delete(); } } zip.close(); }