我有一个奇怪的问题。我想使用类型为PKCS12的Java KeyStore,但是设置类型会导致getCertificate(...)返回null,如果类型设置为JKS,它将返回证书。我错过了我应该为PKCS12实例做的事情吗?
import java.io.ByteArrayInputStream;
import java.security.KeyStore;
import java.security.Provider;
import java.security.Security;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Base64;
public class TestingRandomStuff {
public static void main(String[] args) throws Exception {
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.load(null, null);
String pemStr = "MIICEjCCAXsCAg36MA0GCSqGSIb3DQEBBQUAMIGbMQswCQYDVQQGEwJKUDEOMAwGA1UECBMFVG9reW8xEDAOBgNVBAcTB0NodW8ta3UxETAPBgNVBAoTCEZyYW5rNEREMRgwFgYDVQQLEw9XZWJDZXJ0IFN1cHBvcnQxGDAWBgNVBAMTD0ZyYW5rNEREIFdlYiBDQTEjMCEGCSqGSIb3DQEJARYUc3VwcG9ydEBmcmFuazRkZC5jb20wHhcNMTIwODIyMDUyNjU0WhcNMTcwODIxMDUyNjU0WjBKMQswCQYDVQQGEwJKUDEOMAwGA1UECAwFVG9reW8xETAPBgNVBAoMCEZyYW5rNEREMRgwFgYDVQQDDA93d3cuZXhhbXBsZS5jb20wXDANBgkqhkiG9w0BAQEFAANLADBIAkEAm/xmkHmEQrurE/0re/jeFRLl8ZPjBop7uLHhnia7lQG/5zDtZIUC3RVpqDSwBuw/NTweGyuP+o8AG98HxqxTBwIDAQABMA0GCSqGSIb3DQEBBQUAA4GBABS2TLuBeTPmcaTaUW/LCB2NYOy8GMdzR1mx8iBIu2H6/E2tiY3RIevV2OW61qY2/XRQg7YPxx3ffeUugX9F4J/iPnnu1zAxxyBy2VguKv4SWjRFoRkIfIlHX0qVviMhSlNy2ioFLy7JcPZb+v3ftDGywUqcBiVDoea0Hn+GmxZA";
X509Certificate cert = parseCertificate(pemStr);
ks.setCertificateEntry("CILogon Silver CA 1", cert);
X509Certificate test = (X509Certificate) ks.getCertificate("CILogon Silver CA 1");
//Test is null if KeyStore type is PKCS12, not null if type is JKS
}
private static X509Certificate parseCertificate(String pem) throws Exception {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
byte[] decoded = Base64.getDecoder().decode(pem);
X509Certificate c = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(new ByteArrayInputStream(decoded));
return c;
}
}
编辑:查看源代码后,getCertificate()调用PKCS12KeyStore.engineGetCertificateChain(),它将别名转换为小写。我不认为应该这样做,因为PKCS12可以存储大写字符。我现在必须想出一个解决方法,它看起来像是