shva
shva

Reputation: 539

Verifying Jar signature doesn't work in Java

I had a signed Jar zip containing the following content:

After that I created a tampered Jar file by adding a few characters to image.bin. I tested it with

jarsigner -verify jar.zip

which gave error the error

jarsigner: java.lang.SecurityException: SHA1 digest error for image.bin

which was expected.

Now I need to verify this Jar zip programmingly in Java, and there was an example here. Basically it just opened a Jar file, iterated through the entries and checked for SecuirtyException. However, it didn't give any SecurityException. I am wondering what I may miss here.

Upvotes: 0

Views: 401

Answers (1)

Anya Shenanigans
Anya Shenanigans

Reputation: 94614

I read the source of jarsigner on grepcode, and the following modification of the answer seems to give me consistent results:

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/** @see http://stackoverflow.com/questions/5587656 */
public class Verify {

    public static void main(String[] args) throws IOException {
        System.out.println(verify(new JarFile(args[0])));
    }

    private static boolean verify(JarFile jar) throws IOException {
        Enumeration<JarEntry> entries = jar.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            InputStream is = null;
            byte buffer[] = new byte[8192];
            try {
                is = jar.getInputStream(entry);
                int n;
                while ((n = is.read(buffer, 0, buffer.length)) != -1) {
                }
            } catch (SecurityException se) {
                return false;
            } finally {
                if (is != null) {
                    is.close();
                }
            }
        }
        return true;
    }
}

i.e. if you read the content of the entry it will trigger the check.

Upvotes: 3

Related Questions