Women in Technology

Hear us Roar



Article:
  Programmatically Signing JAR Files
Subject:   Private Key ?
Date:   2003-04-16 05:52:06
From:   anonymous2
Response to: Private Key ?

I've just gone through the same exercise. Here is my solution assuming you've already generated a private key using KeyTool.


public static void main(String args[])
{
try
{
FileInputStream fileIn = new FileInputStream("keytoolgenerated.keystore");
KeyStore keyStore = KeyStore.getInstance("JKS");
char[] password = {'p','a','s','s','w','d'};
keyStore.load(fileIn, password);
Certificate[] chain = keyStore.getCertificateChain("alias");
X509Certificate certChain[] = new X509Certificate[chain.length];


CertificateFactory cf = CertificateFactory.getInstance("X.509");
for (int count = 0; count < chain.length; count++)
{
ByteArrayInputStream certIn = new ByteArrayInputStream(chain[0].getEncoded());
X509Certificate cert = (X509Certificate)cf.generateCertificate(certIn);
certChain[count] = cert;
}


Key key = keyStore.getKey("alias",password);
KeyFactory keyFactory = KeyFactory.getInstance(key.getAlgorithm());
KeySpec keySpec = keyFactory.getKeySpec(key, DSAPrivateKeySpec.class);
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
JARSigner jarSigner = new JARSigner("alias", privateKey, certChain);


JarFile jarFile = new JarFile("MyJar.jar");
OutputStream outStream = new FileOutputStream("MySignedJar.jar");
jarSigner.signJarFile(jarFile, outStream);
fileIn.close();
}
catch(Throwable ex)
{
ex.printStackTrace();
}
}


Good luck.


Mark Nadelson
unixnttalk@yahoo.com