I'm using the following code to verify a X509Certificate
as per the references here.
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);
}
This works If I remove the provider BC
while getting the instance of CertPathBuilder
and let JVM use the default SUN
provider. However with BC
provider I get the following exception.
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)
Any ideas how can I make this work with BouncyCastle provider?
The certificate to validate has to be in the CertStore in your example so add this:
parameters.setRevocationEnabled...;
//Add the certitificate to the cert store
intermediateCerts.add(certificate);
CertStore intermediateCertStore....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With