我試圖以編程方式驗證一個jar文件沒有被明顯篡改。我有兩個我想防止的用例。 1)現有類別的修改 2)在罐子中添加新類別驗證Jar簽名
我使用jarsigner在jar中籤名。當我使用jarsigner驗證上述任何一種情況時,它的工作方式與我所期望的相同。
當我嘗試這樣做編程方式使用樣本然而 How to verify a jar signed with jarsigner programmatically 或 How to verify signature on self signed jar? ,我完全不爲此事得到任何SecurityExceptions ......或任何異常。
不知道我在做什麼錯,因爲這些片段似乎適用於其他人。有任何想法嗎?這是JDK 1.6順便說一句。
編輯: 如下要求,代碼樣本...提供自己的改型罐:)
JarFile myJar;
try
{
//Insert the full path to the jar here
String libPath = ""
stature = new JarFile(libPath,true);
//Don't really need this right now but was using it to inspect the SHA1 hashes
InputStream is = myJar.getInputStream(myJar.getEntry("META-INF/MANIFEST.MF"));
Manifest man = myJar.getManifest();
is.close();
verifyJar(myJar);
}
catch (IOException ioe)
{
throw new Exception("Cannot load jar file", ioe);
}
private void verifyJar(JarFile jar) throws Exception
{
Enumeration<java.util.jar.JarEntry> entries = jar.entries();
while (entries.hasMoreElements())
{
java.util.jar.JarEntry entry = entries.nextElement();
try
{
jar.getInputStream(entry);
//Also tried actually creating a variable from the stream in case it was discarding it before verification
//InputStream is = jar.getInputStream(entry);
//is.close();
}
catch (SecurityException se)
{
/* Incorrect signature */
throw new Exception("Signature verification failed", se);
}
catch (IOException ioe)
{
throw new Exception("Cannot load jar file entry", ioe);
}
}
}
你是如何篡改受測JAR的? – trashgod 2011-04-07 21:49:53
我用7zip打開它。我添加了一個新的包目錄,其中包含一些類文件,並用重新編譯的版本修改了一些現有的類文件。 – Amasuriel 2011-04-07 21:52:26
如果'jarsigner'拒絕了更改後的JAR,但是您的代碼接受它,[sscce](http://sscce.org/)可能有助於發現問題。 – trashgod 2011-04-07 21:56:14