Skip to content

Instantly share code, notes, and snippets.

@jdavidzapatab
Last active August 25, 2022 20:20
Show Gist options
  • Save jdavidzapatab/2afddc11c5ccaa8850060386e8a65de1 to your computer and use it in GitHub Desktop.
Save jdavidzapatab/2afddc11c5ccaa8850060386e8a65de1 to your computer and use it in GitHub Desktop.

Sign Jars using Gradle

To sign one or more jar files using the jarsigner tool (part of any JDK), follow these instructions. Notice this set of instructions assume you already have the needed KeyStore with the corresponding Code Signing certificate, the KeyStore and certificate key password, and you know the alias of the Key to use from the KeyStore.

  • Make sure to have a KeysStore with your Code Signing certificate, associated passwords, etc.
  • Add the following properties to your Gradle project. Remember you probably don't want your private credentials in your versioning system:
org.gradle.warning.mode=all

jarsigner=C:/path/to/java8bin/jarsigner.exe
keyStore=C:/path/to/keystore.jks
keyStoreAlias=your_keystore_alias
keyStorePass=your_keystore_password
keyStoreKeyPass=your_key_password
tsa=http://time.certum.pl
  • The org.gradle.warning.mode=all property just shows all warnings when running your Gradle tasks, which may help you prevent the usage of deprecated features.
  • Replace these values with your actual paths and values. Set the Time Stamping Authority (TSA) to whatever you prefer.
  • Now add the following new tasks to your build.gradle file:
tasks.register("signFatJar") {
    def exec_line = [project.jarsigner, "-keystore", project.keyStore,
                     "-storepass", project.keyStorePass, "-keypass", project.keyStoreKeyPass,
                     "-tsa", project.tsa, "-verbose",
                     "$buildDir/libs/*.jar", project.keyStoreAlias].execute()
    exec_line.waitFor()

    println "Exit value: ${exec_line.exitValue()}"
    println "Output: ${exec_line.text}"
}

tasks.register("verifySignedFatJar") {
    def exec_line = [project.jarsigner, "-verbose", "-verify", "$buildDir/libs/*.jar"].execute()
    exec_line.waitFor()

    println "Exit value: ${exec_line.exitValue()}"
    println "Output: ${exec_line.text}"
}
  • Those are the tasks to run the Jar signature, and the Verification of the signed Jars. You can see each exec_line array simply adds all the parameters in order. You can play with those arrays to use more or less options. I used the "$buildDir/libs/*.jar" string to define the path to my Jar files, you can change it to anything you prefer.
  • Then just run the correct tasks when needed.

Credits

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment