Creating the signed JAR

Now we can actually create and output the signed JAR file. The
signJarFile method is the publicly accessible method
which propagates all the exceptions which may occur when signing the
JAR file. First we need to compute all the necessary files to go into
the META-INF directory for the signed JAR. Next we write
out the contents of the META-INF directory (the
MANIFEST.MF file, the SF, the
DSA file, and the rest of the files that were originally
in the META-INF directory), and then we will iterate,
writing out the rest of the JAR.

// the actual JAR signing method -- this is the method which
// will be called by those wrapping the JARSigner class
public void signJarFile( JarFile jarFile, OutputStream outputStream )
throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, IOException {

// calculate the necessary files for the signed jAR

// get the manifest out of the jar and verify that
// all the entries in the manifest are correct
Manifest manifest = getManifestFile( jarFile );
Map entries = createEntries( manifest, jarFile );

// finish the stream that we have been writing to
jos.flush();
jos.finish();

// close the JAR file that we have been using
jarFile.close();

}

}

And that's it. Using this class, JAR files can be signed from
within different applications; their error conditions are exposed so
they may be caught and dealt with in a more robust way than that which
is provided by the Java libraries themselves.

Raffi Krikorian
makes a career of hacking everything and anything. Professionally,
he is the founding partner at Synthesis Studios: a technological design
and consulting firm that orchestrates his disjointed train of thought.