/**
* 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.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.Key;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.util.Enumeration;
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 = "D:\\OpenSSL\\cq\\cert.pfx"; //证书路径
public static final String KEYSTORE_PASSWORD = "1111"; //证书密码
// JKS output file
public static final String OUTPUT_KEYSTORE_FILE = "D:\\OpenSSL\\cq\\cert_new.keystore"; //导出证书路径
public static final String OUTPUT_KEYSTORE_PASSWORD = "xxxxxx"; //导出证书密码
public static final String OUTPUT_KEY_ALIAS = "cert_new"; //证书别名
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();
//----------------------------------------------------------------------
// get a JKS keystore and initialize it.
KeyStore outputKeyStore = KeyStore.getInstance("JKS");
// outputKeyStore.load(new FileInputStream(OUTPUT_KEYSTORE_FILE), "changeit".toCharArray());
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 <-- Certificate window <-- view <-- Certificate
// Button <-- Content tab <-- Internet Options <-- Tools menu
// In MS IE 6.
Enumeration enumd = inputKeyStore.aliases();
while (enumd.hasMoreElements()) // we are readin just one certificate.
{
String keyAlias = (String)enumd.nextElement();
System.out.println("alias=[" + keyAlias + "]");
if (inputKeyStore.isKeyEntry(keyAlias))
{
Key key = inputKeyStore.getKey(keyAlias, nPassword);
Certificate[] certChain = inputKeyStore.getCertificateChain(keyAlias);
System.out.println("key.format=" + key.getFormat());
System.out.println("" + new String(key.getAlgorithm()));
outputKeyStore.setKeyEntry(OUTPUT_KEY_ALIAS, key, OUTPUT_KEYSTORE_PASSWORD.toCharArray(), certChain);
}
}
FileOutputStream out = new FileOutputStream(OUTPUT_KEYSTORE_FILE);
outputKeyStore.store(out, OUTPUT_KEYSTORE_PASSWORD.toCharArray());
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}