在 pkcs12 密钥库中保存证书链
2022-09-01 23:44:06
下面的代码:
//used Bouncy Castle provider for keyStore
keyStore.setKeyEntry(alias, (Key)keyPair.getPrivate(), pwd, certChain);
其中,certChain 保存结束证书和颁发者证书(即两个证书),
如果 keyStore 是 的实例,则不会将颁发者证书作为链的一部分保存在保存到文件系统密钥库文件中。PKCS12
如果密钥库类型为 ,则它会保存这两个证书。这是为什么呢?难道 PKCS12 不是假设两个证书都是链的一部分吗?PKCS12-3DES-3DES
编辑:这是一个SSCCE。这适用于 ,失败,只有链中的第一个证书可以通过 访问。打开保存的文件时,可以同时显示两个证书。"JKS"
"PKCS12"
getCertificateChain(String)
openssl pkcs12
public void testKeyStore() {
try {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
Certificate[] outChain = { createCertificate("CN=CA", publicKey, privateKey), createCertificate("CN=Client", publicKey, privateKey) };
KeyStore outStore = KeyStore.getInstance("PKCS12");
outStore.load(null, "secret".toCharArray());
outStore.setKeyEntry("mykey", privateKey, "secret".toCharArray(), outChain);
OutputStream outputStream = new FileOutputStream("c:/outstore.pkcs12");
outStore.store(outputStream, "secret".toCharArray());
outputStream.flush();
outputStream.close();
KeyStore inStore = KeyStore.getInstance("PKCS12");
inStore.load(new FileInputStream("c:/outstore.pkcs12"), "secret".toCharArray());
Key key = outStore.getKey("myKey", "secret".toCharArray());
assertEquals(privateKey, key);
Certificate[] inChain = outStore.getCertificateChain("mykey");
assertNotNull(inChain);
assertEquals(outChain.length, inChain.length);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
private static X509Certificate createCertificate(String dn, PublicKey publicKey, PrivateKey privateKey) throws Exception {
X509V3CertificateGenerator certGenerator = new X509V3CertificateGenerator();
certGenerator.setSerialNumber(new BigInteger("1"));
certGenerator.setIssuerDN(new X509Name(dn));
certGenerator.setSubjectDN(new X509Name(dn));
certGenerator.setNotBefore(Calendar.getInstance().getTime());
certGenerator.setNotAfter(Calendar.getInstance().getTime());
certGenerator.setPublicKey(publicKey);
certGenerator.setSignatureAlgorithm("SHA1withRSA");
X509Certificate certificate = (X509Certificate)certGenerator.generate(privateKey, "BC");
return certificate;
}