Java中默认keystore类型是JKS格式,CA签发设备证书和个人证书通常是PFX格式,有时需要相互转换。
可以用于转换的工具有keytool或者openssl命令行工具,另外JDK自身也提供了一组API,可以实现各类型相互转换;
以下代码时间将JKS读取为PFX格式到内存:
?
class="java" name="code">public String readJKSAsPfx(String JKSPath,String pwd){
String default_pfx_site_certificate_pwd = "11111111";
StringBuffer b64pfxBuf = new StringBuffer();
KeyStore keyStore = KeyStore.getInstance("JKS");
File file = new File(keyStorePath);
keyStore.load(JKSPath, pwd);
Enumeration<String> emuAlias = keyStore.aliases();
KeyStore.Entry jentry = null;
while (emuAlias.hasMoreElements()) {
String alias = (String) emuAlias.nextElement();
if (keyStore.isKeyEntry(alias)) {
jentry = keyStore.getEntry(alias, new PasswordProtection(pwd.toCharArray()));
//转换为pfx
KeyStore p12 = KeyStore.getInstance("PKCS12");
p12.load(null);//初始化keystroe
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//输出到字节数组
p12.setEntry("p12", jentry, new PasswordProtection(pwd.toCharArray()));
p12.store(baos, default_pfx_site_certificate_pwd.toCharArray());
b64pfxBuf.append(java.util.Base64.getEncoder().encodeToString(baos.toByteArray()));
break;
}
}
return b64pfxBuf.toString();
}
?