我需要从我的应用程序中验证一个签名的 jar。我发现我可以通过阅读所有内容来做到这一点,如下所示:
public boolean verifyJar(String filePath) {
try {
JarFile jar = new JarFile(filePath, true);
Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
InputStream is = jar.getInputStream(entry);
byte[] buffer = new byte[10000];
while (is.read(buffer, 0, buffer.length) != -1) {
// we just read. this will throw a SecurityException
// if a signature/digest check fails.
}
is.close();
}
return true;
} catch (Exception e) {
return false;
}
}
如果我使用有效的 jar 执行检查器,它就会通过。如果我通过将罐子切成两半来破坏罐子,它就会失败。但是,如果我在一个进程中同时执行这两项操作,则第二次检查通过(就好像它读取了文件的先前版本一样)!
public static void main(String[] args) throws Exception {
String path = "src/test/resources/temp/lib.jar";
// Passes - that's good
System.out.println(new Validator().verifyJar(path));
byte[] content = FileUtil.readFile(path);
FileUtil.save(path, Arrays.copyOf(content, content.length / 2));
// Passes - but it shouldn't.
// Fails if the first check is commented out though.
System.out.println(new Validator().verifyJar(path));
}
所以它看起来像ZipFile
或JarFile
以某种方式被缓存。如何抑制这种行为?