Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you programmatically sign jar files in Java?

Tags:

java

jar

sign

Has anyone done this before? The only reference I have found on google has been: http://onjava.com/onjava/2001/04/12/signing_jar.html which still uses sun.* classes that will cause issues...

Found this as well, but does not work with java16: https://svn.cs.cf.ac.uk/projects/whip/trunk/whip-core/src/main/java/org/whipplugin/data/bundle/JarSigner15.java

like image 729
wuntee Avatar asked Oct 07 '11 14:10

wuntee


3 Answers

To address a sudden change of security restrictions in WebStart applications in Java 7u45 we have created a simple signed jar file generator. It uses Guava 15 and Bouncy Castle bcpkix module. It should run on Java 6 & 7. It is suitable for small files only. Use it for any purpose you want.

like image 147
mmm444 Avatar answered Sep 28 '22 19:09

mmm444


Be aware that the sun.security.tools.JarSigner class was written to be used as a command-line utility and wasn't designed to be called from Java code. As a result, the error handling is pretty abrupt: the code will simply print an error message to standard out and then call System.exit() 1.

This means that if you call the class from within your Java code and an error occurs when you try to sign a jar, the JVM running your code will simply stop. This may be fine depending on your situation, but if your code is long running or acting as a service, it's not so good.

It's therefore better to call the jarsigner tool using the ProcessBuilder as per clamp's comment. You can then call waitFor() on the resulting Process object and check exitValue() to see if the command was successful. getInputStream() will let you read any error messages that were written to standard out if the operation fails.

like image 29
alphaloop Avatar answered Sep 28 '22 20:09

alphaloop


In the tools.jar file is the class sun.security.tools.JarSigner which has a static run(ava.lang.String[] strings) method that takes the same parameters as the jarsigner executable does.

So you can call something like:

sun.security.tools.JarSigner.run(new String[] {
    "-keystore", keystoreFile.getAbsolutePath(),
    "-storepass", keystorePassword,
    outFile.getAbsolutePath(),
    keystoreAlias 
});

You need to make sure tools.jar is in your classpath for compiling and execution.

like image 31
Nathan Voxland Avatar answered Sep 28 '22 19:09

Nathan Voxland