我使用以下代码根据参考here验证X509Certificate
。
static void verifyCertTrust(X509Certificate certificate, Set<X509Certificate> additionalCerts) throws CertificateException, NoSuchAlgorithmException, NoSuchProviderException, CertPathValidatorException, InvalidAlgorithmParameterException, CertPathBuilderException{
Set<X509Certificate> trustedRoots = new HashSet<X509Certificate>();
Set<X509Certificate> intermediateCerts = new HashSet<X509Certificate>();
for (X509Certificate cert : additionalCerts) {
if(isSelfSigned(cert)){
trustedRoots.add(cert);
}
else{
intermediateCerts.add(cert);
}
}
Set<TrustAnchor> trustAnchors = new HashSet<TrustAnchor>();
for (X509Certificate root : trustedRoots) {
trustAnchors.add(new TrustAnchor(root, null));
}
X509CertSelector selector = new X509CertSelector();
selector.setCertificate(certificate);
PKIXParameters parameters = new PKIXBuilderParameters(trustAnchors, selector);
parameters.setRevocationEnabled(false);
CertStore intermediateCertStore = CertStore.getInstance("Collection", new CollectionCertStoreParameters(intermediateCerts), "BC");
parameters.addCertStore(intermediateCertStore);
CertPathBuilder cpb = CertPathBuilder.getInstance("PKIX", "BC");
cpb.build(parameters);
}
这有效如果我在获取BC
的实例时删除提供程序CertPathBuilder
并让JVM使用默认的SUN
提供程序。但是对于BC
提供程序,我得到以下异常。
Exception in thread "main" java.security.cert.CertPathBuilderException: No certificate found matching targetContraints.
at org.bouncycastle.jce.provider.PKIXCertPathBuilderSpi.engineBuild(Unknown Source)
at java.security.cert.CertPathBuilder.build(Unknown Source)
at signer.GetPkcs11Key.verifyCertTrust(GetPkcs11Key.java:105)
at signer.GetPkcs11Key.main(GetPkcs11Key.java:71)
任何想法如何才能与BouncyCastle提供商合作?
答案 0 :(得分:4)
要验证的证书必须位于示例中的CertStore中,因此请添加:
parameters.setRevocationEnabled...;
//Add the certitificate to the cert store
intermediateCerts.add(certificate);
CertStore intermediateCertStore....