How do you programmatically sign jar files in Java?

前端 未结 4 2014
面向向阳花
面向向阳花 2021-01-12 03:33

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 wil

相关标签:
4条回答
  • 2021-01-12 03:55

    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.

    0 讨论(0)
  • 2021-01-12 04:03

    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.

    0 讨论(0)
  • 2021-01-12 04:14

    I'm using the SingJar Ant task (which apparently calls the command line tool underneath). It should be possible to call that programmatically.

    0 讨论(0)
  • 2021-01-12 04:18

    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.

    0 讨论(0)
提交回复
热议问题