我需要从我的应用程序验证一个签名的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是以某种方式缓存的。如何抑制此行为?
发布于 2011-06-08 16:25:55
ZipFile必须关闭,这样本机代码才不会缓存。如果路径和File.lastModified相同,Iirc ZipFile会包装相同的句柄(jzfile)。
或者,触摸File.lastModified也可以做到这一点,但手动关闭任何打开的东西(包括。ZipFile)对于防止资源泄漏是必要的。
https://stackoverflow.com/questions/6275838
复制相似问题