Signing jars with a Netbeans Ant script

Digitally signing a jar file is one step among many before releasing your jar to the world. It can help you identify your program as one that genuinely came from you. It can also make it harder for people to alter the program (although not impossible). I recently went through this process with OBZVault where I integrated signing into the build process (Ant scripts generated by NetBeans).

Firstly you should do some background reading. There is a great article at onjava.com that covers Java vs .NET Security mechanisms. If you are familiar with .NET Security this is a very good intro into the Java world. The tool that does the signing of jars is called jarsigner, and key stores are created with keytool.

Next you need to:

a) Create the keystore with keytool.

keytool -genkey -alias -keyalg RSA -keystore -validity 365

The keystore filename is usually a jks file, but you can call it anything. Remember the alias name you used for later. To check that the store is created correctly use the following command to view the contents:

keytool -list -v -keystore

b) Integrate jarsigner into your build system. If you developed your application in NetBeans 6.5 you will have a build.xml file in the root of your project. Add the following targets to build.xml:

<target name="-post-jar" depends="signjar">
</target>

<target name="signjar" depends="">
<echo message="Signing ${dist.dir}/application.jar ..."/>
<exec dir="${work.dir}" executable="jarsigner">
<arg value="-verbose" />
<arg value="-keystore" />
<arg value="keystore_file.jks" />
<arg value="-storepass" />
<arg value="store_password" />
<arg value="-keypass" />
<arg value="keypass" />
<arg value="application.jar" />
<arg value="alias_name" />
</exec>
</target>

That’s all folks. Next time I’ll discuss code obfuscation which can be integrated into build.xml as well.