Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verify and Sign a Jar programmatically

I am new to this topic, therefore I hope I use the right vocabulary. Is it possible to get the possibility of Jarsigner within Java self?

I need the possibility to do the following things programatically:

  • verify if a jar is signed with a certain private key from a keystore
  • if the jar is verified: unsign the jar
  • sign the jar with another private key from an official certificate authority, which is in the same or in another keystore

In pseudo-code I imagine something like this:

JarVerifier verifier = new JarVerifier(/*all needed parameters like the location of the keystore*/);
verifier.verify(jarFile); //returns a value which indicates the result (an Enum or an integer value)

Signing the jar should work in a similar way:

JarSigner signer = new JarSigner(/*all needed parameters like the location of the keystore, passwords, alias*/);
signer.sign(jarFile);

I know that this is a duplicate of many other questions, but I am not happy with their answers. The solution of these answers is in most cases a self-written class, a modification of a class found from OpenJDK or a hint that the code needs still to be written and how this can be done. This is not acceptable for me, because they are not maintained (or I have to write and maintain the classes myself), I know nothing about their correctness (especially if I have to write the code myself) and license issues.

What I don't get is that there seems to be no easy solution provided by Oracle, especially as it is such a critical topic, where an error might lead to an insecure system.

like image 228
gillesB Avatar asked Nov 11 '22 13:11

gillesB


1 Answers

I try to answer the question myself.

Verifying

To verify the Jar there seems not be be a good ready-to use solution. Therefore own code needs to be written.

Signing

There is the Ant Task SignJar which is able to sign jars and it is possible to use Ant Tasks inside Java

The class to sign the jars can look like this:

public class JarSigner extends SignJar {

public JarSigner() {
    project = new Project();
    project.init();
    taskType = "signJar";
    taskName = "signJar";
    target = new Target();
}

public static void signJar(File jarToSign, String alias, String keypass, String keystore, String storepass) {
    JarSigner signer = new JarSigner();
    signer.setJar(jarToSign);
    signer.setAlias(alias);
    signer.setKeypass(keypass);
    signer.setKeystore(keystore);
    signer.setStorepass(storepass);
    signer.setSignedjar(jarToSign);
    signer.execute();
}
}

unsigning

Did not need it yet.

like image 134
gillesB Avatar answered Nov 15 '22 12:11

gillesB