正在从信任库验证 Java 中的证书链

Validating certificate chain in Java from truststore

我有一个证书链作为 der 编码的 byte[][] 数组来验证。我还有一个信任库文件。

在我从该字节数组[][] 创建 X509Certificate[] 并初始化 trustmanager 之后,我将如何告诉 TrustManager 验证 X509Certificate[]?正确的做法是什么?

谢谢。

示例代码:

int certVerify(byte certChain[][])
{
   CertificateFactory cf = CertificateFactory.getInstance("X509");
   X509Certificate certx[] = new X509Certificate[10];
   for(int i=0;i<certChain.length;i++)
   {
     certx[i] = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(certChain[i]));
   }

   KeyStore keyStore = KeyStore.getInstance("JKS");
   keyStore.load( new FileInputStream("cacerts.jks"),"123456".toCharArray());

   TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
   trustManagerFactory.init(keyStore);
}

关于如何实现一个 here

有一些很好的信息

或者您可以按照说明使用 BouncyCastle API here

您需要使用必要的系统属性启用 OCSP,或者为链中的每个证书获取 CRL,以便检查吊销状态。 (或者,您可以禁用吊销检查,但会带来风险。)

CertificateFactory cf = CertificateFactory.getInstance("X.509");
List<Certificate> certx = new ArrayList<>(certChain.length);
for (byte[] c : certChain)
  certx.add(cf.generateCertificate(new ByteArrayInputStream(c)));
CertPath path = cf.generateCertPath(certx);
CertPathValidator validator = CertPathValidator.getInstance("PKIX");
KeyStore keystore = KeyStore.getInstance("JKS");
try (InputStream is = Files.newInputStream(Paths.get("cacerts.jks"))) {
  keystore.load(is, "changeit".toCharArray());
}
Collection<? extends CRL> crls;
try (InputStream is = Files.newInputStream(Paths.get("crls.p7c"))) {
  crls = cf.generateCRLs(is);
}
PKIXParameters params = new PKIXParameters(keystore);
CertStore store = CertStore.getInstance("Collection", new CollectionCertStoreParameters(crls));
/* If necessary, specify the certificate policy or other requirements 
 * with the appropriate params.setXXX() method. */
params.addCertStore(store);
/* Validate will throw an exception on invalid chains. */
PKIXCertPathValidatorResult r = (PKIXCertPathValidatorResult) validator.validate(path, params);