This is my testing, working code.
package cert;
/**
* Convert PKCS12 format digital certificate(treated as a PKCS12 keystore)
* to a JKS format keystore, which could be used in JSSE(Although JSSE has
* a tool to recognize PKCS12, internally it's using JKS format).
*/
import java.security.KeyStore;
import java.security.Key;
import java.security.cert.Certificate;
import java.io.*;
import java.util.*;
public class ConvertPKCS12ToJKS
{
//certificate store format
public static final String PKCS12 = "PKCS12";
public static final String JKS = "JKS";
// PKCS12 keystore properties
public static final String INPUT_KEYSTORE_FILE = "cert/geotrustadmintest4.pfx"; //"cert/dev_coo1.p12";
public static final String KEYSTORE_PASSWORD = "changeit"; //"123";
// JKS output file
public static final String OUTPUT_KEYSTORE_FILE = "cert/geotrustadmintest4.jks";
public static void main(String[] args)
{
try
{
KeyStore inputKeyStore = KeyStore.getInstance("PKCS12");
FileInputStream fis = new FileInputStream(INPUT_KEYSTORE_FILE);
// If the keystore password is empty(""), then we have to set
// to null, otherwise it won't work!!!
char[] nPassword = null;
if ((KEYSTORE_PASSWORD == null) || KEYSTORE_PASSWORD.trim().equals(""))
{
nPassword = null;
}
else
{
nPassword = KEYSTORE_PASSWORD.toCharArray();
}
inputKeyStore.load(fis, nPassword);
fis.close();
System.out.println("keystore type=" + inputKeyStore.getType());
//----------------------------------------------------------------------
// get a JKS keystore and initialize it.
KeyStore outputKeyStore = KeyStore.getInstance("JKS");
outputKeyStore.load(null, "changeit".toCharArray());
// Now we loop all the aliases, we need the alias to get keys.
// It seems that this value is the "Friendly name" field in the
// detals tab
// Button
// In MS IE 6.
Enumeration enum = inputKeyStore.aliases();
while (enum.hasMoreElements()) // we are readin just one certificate.
{
String keyAlias = (String)enum.nextElement();
System.out.println("alias=[" + keyAlias + "]");
if (inputKeyStore.isKeyEntry(keyAlias))
{
Key key = inputKeyStore.getKey(keyAlias, nPassword);
Certificate[] certChain = inputKeyStore.getCertificateChain(keyAlias);
outputKeyStore.setKeyEntry("dev", key, "changeit".toCharArray(), certChain);
}
}
FileOutputStream out = new FileOutputStream(OUTPUT_KEYSTORE_FILE);
outputKeyStore.store(out, nPassword);
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}