List of usage examples for java.security.cert CollectionCertStoreParameters CollectionCertStoreParameters
public CollectionCertStoreParameters(Collection<?> collection)
From source file:org.ejbca.extra.db.ExtRAMsgHelper.java
/** * Method that signes the given data using the algorithm specified in the init method. * //from w w w. java 2 s.com * @param signKey, the key used to sign the data * @param signCert the certificate * @param data * @return the signed data or null if signature failed */ public static byte[] signData(PrivateKey signKey, X509Certificate signCert, byte[] data) { byte[] retdata = null; try { ArrayList certList = new ArrayList(); certList.add(signCert); CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), provider); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); gen.addCertificatesAndCRLs(certs); gen.addSigner(signKey, signCert, signAlg); CMSSignedData signedData = gen.generate(new CMSProcessableByteArray(data), true, provider); retdata = signedData.getEncoded(); } catch (Exception e) { log.error("Error signing data : ", e); } return retdata; }
From source file:org.ejbca.extra.db.ExtRAMsgHelper.java
/** * Method used to verify signed data./* w ww . ja va 2s.co m*/ * * @param TrustedCACerts a Collection of trusted certificates, should contain the entire chains * @param TrustedCRLs a Collection of trusted CRLS, use null if no CRL check should be used. * @param signedData the data to verify * @param date the date used to check the validity against. * @return a ParsedSignatureResult. */ public static ParsedSignatureResult verifySignature(Collection cACertChain, Collection trustedCRLs, byte[] signedData, Date date) { boolean verifies = false; X509Certificate usercert = null; ParsedSignatureResult retval = new ParsedSignatureResult(false, null, null); byte[] content = null; try { // First verify the signature CMSSignedData sp = new CMSSignedData(signedData); CertStore certs = sp.getCertificatesAndCRLs("Collection", "BC"); SignerInformationStore signers = sp.getSignerInfos(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ((CMSProcessableByteArray) sp.getSignedContent()).write(baos); content = baos.toByteArray(); baos.close(); Collection c = signers.getSigners(); Iterator it = c.iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); Collection certCollection = certs.getCertificates(signer.getSID()); Iterator certIt = certCollection.iterator(); usercert = (X509Certificate) certIt.next(); boolean validalg = signer.getDigestAlgOID().equals(signAlg); verifies = validalg && signer.verify(usercert.getPublicKey(), "BC"); } // Second validate the certificate X509Certificate rootCert = null; Iterator iter = cACertChain.iterator(); while (iter.hasNext()) { X509Certificate cert = (X509Certificate) iter.next(); if (cert.getIssuerDN().equals(cert.getSubjectDN())) { rootCert = cert; break; } } if (rootCert == null) { throw new CertPathValidatorException("Error Root CA cert not found in cACertChain"); } List list = new ArrayList(); list.add(usercert); list.add(cACertChain); if (trustedCRLs != null) { list.add(trustedCRLs); } CollectionCertStoreParameters ccsp = new CollectionCertStoreParameters(list); CertStore store = CertStore.getInstance("Collection", ccsp); //validating path List certchain = new ArrayList(); certchain.addAll(cACertChain); certchain.add(usercert); CertPath cp = CertificateFactory.getInstance("X.509", "BC").generateCertPath(certchain); Set trust = new HashSet(); trust.add(new TrustAnchor(rootCert, null)); CertPathValidator cpv = CertPathValidator.getInstance("PKIX", "BC"); PKIXParameters param = new PKIXParameters(trust); param.addCertStore(store); param.setDate(date); if (trustedCRLs == null) { param.setRevocationEnabled(false); } else { param.setRevocationEnabled(true); } cpv.validate(cp, param); retval = new ParsedSignatureResult(verifies, usercert, content); } catch (Exception e) { log.error("Error verifying data : ", e); } return retval; }
From source file:org.ejbca.extra.ra.ScepRAServlet.java
private byte[] createPKCS7(Certificate[] chain, PrivateKey pk, X509Certificate cert) throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException, CertStoreException, CMSException, IOException { Collection<Certificate> certList = Arrays.asList(chain); CMSProcessable msg = new CMSProcessableByteArray(new byte[0]); CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC"); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); gen.addCertificatesAndCRLs(certs);//from w ww .j a va2 s .c o m // it is possible to sign the pkcs7, but it's not currently used CMSSignedData s = null; if ((pk != null) && (cert != null)) { gen.addSigner(pk, cert, CMSSignedDataGenerator.DIGEST_MD5); s = gen.generate(msg, true, "BC"); } else { s = gen.generate(msg, "BC"); } return s.getEncoded(); }
From source file:org.josso.auth.scheme.validation.CRLX509CertificateValidator.java
public void validate(X509Certificate certificate) throws X509CertificateValidationException { try {/* w w w . jav a 2 s . com*/ URL crlUrl = null; if (_url != null) { crlUrl = new URL(_url); log.debug("Using the CRL server at: " + _url); } else { log.debug("Using the CRL server specified in the certificate."); System.setProperty("com.sun.security.enableCRLDP", "true"); } // configure the proxy if (_httpProxyHost != null && _httpProxyPort != null) { System.setProperty("http.proxyHost", _httpProxyHost); System.setProperty("http.proxyPort", _httpProxyPort); } else { System.clearProperty("http.proxyHost"); System.clearProperty("http.proxyPort"); } // get certificate path CertPath cp = generateCertificatePath(certificate); // get trust anchors Set<TrustAnchor> trustedCertsSet = generateTrustAnchors(); // init PKIX parameters PKIXParameters params = new PKIXParameters(trustedCertsSet); // activate certificate revocation checking params.setRevocationEnabled(true); // disable OCSP Security.setProperty("ocsp.enable", "false"); // get a certificate revocation list if (crlUrl != null) { URLConnection connection = crlUrl.openConnection(); connection.setDoInput(true); connection.setUseCaches(false); DataInputStream inStream = new DataInputStream(connection.getInputStream()); CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509CRL crl = (X509CRL) cf.generateCRL(inStream); inStream.close(); params.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(Collections.singletonList(crl)))); } // perform validation CertPathValidator cpv = CertPathValidator.getInstance("PKIX"); PKIXCertPathValidatorResult cpvResult = (PKIXCertPathValidatorResult) cpv.validate(cp, params); X509Certificate trustedCert = (X509Certificate) cpvResult.getTrustAnchor().getTrustedCert(); if (trustedCert == null) { log.debug("Trsuted Cert = NULL"); } else { log.debug("Trusted CA DN = " + trustedCert.getSubjectDN()); } } catch (CertPathValidatorException e) { log.error(e, e); throw new X509CertificateValidationException(e); } catch (Exception e) { log.error(e, e); throw new X509CertificateValidationException(e); } log.debug("CERTIFICATE VALIDATION SUCCEEDED"); }
From source file:org.josso.auth.scheme.validation.OCSPX509CertificateValidator.java
public void validate(X509Certificate certificate) throws X509CertificateValidationException { try {// w w w . j ava 2 s . c o m if (_url != null) { log.debug("Using the OCSP server at: " + _url); Security.setProperty("ocsp.responderURL", _url); } else { log.debug("Using the OCSP server specified in the " + "Authority Info Access (AIA) extension " + "of the certificate"); } // configure the proxy if (_httpProxyHost != null && _httpProxyPort != null) { System.setProperty("http.proxyHost", _httpProxyHost); System.setProperty("http.proxyPort", _httpProxyPort); } else { System.clearProperty("http.proxyHost"); System.clearProperty("http.proxyPort"); } // get certificate path CertPath cp = generateCertificatePath(certificate); // get trust anchors Set<TrustAnchor> trustedCertsSet = generateTrustAnchors(); // init PKIX parameters PKIXParameters params = new PKIXParameters(trustedCertsSet); // init cert store Set<X509Certificate> certSet = new HashSet<X509Certificate>(); if (_ocspCert == null) { _ocspCert = getCertificate(_ocspResponderCertificateAlias); } if (_ocspCert != null) { certSet.add(_ocspCert); CertStoreParameters storeParams = new CollectionCertStoreParameters(certSet); CertStore store = CertStore.getInstance("Collection", storeParams); params.addCertStore(store); Security.setProperty("ocsp.responderCertSubjectName", _ocspCert.getSubjectX500Principal().getName()); } // activate certificate revocation checking params.setRevocationEnabled(true); // activate OCSP Security.setProperty("ocsp.enable", "true"); // perform validation CertPathValidator cpv = CertPathValidator.getInstance("PKIX"); PKIXCertPathValidatorResult cpvResult = (PKIXCertPathValidatorResult) cpv.validate(cp, params); X509Certificate trustedCert = (X509Certificate) cpvResult.getTrustAnchor().getTrustedCert(); if (trustedCert == null) { log.debug("Trsuted Cert = NULL"); } else { log.debug("Trusted CA DN = " + trustedCert.getSubjectDN()); } } catch (CertPathValidatorException e) { log.error(e, e); throw new X509CertificateValidationException(e); } catch (Exception e) { log.error(e, e); throw new X509CertificateValidationException(e); } log.debug("CERTIFICATE VALIDATION SUCCEEDED"); }
From source file:org.signserver.module.xades.signer.XAdESSignerUnitTest.java
@Test public void testProcessData_basicSigningXAdESFormT() throws Exception { LOG.info("testProcessData_basicSigningXAdESFormT"); XAdESSigner instance = new MockedXAdESSigner(tokenRSA); WorkerConfig config = new WorkerConfig(); config.setProperty("XADESFORM", "T"); config.setProperty("TSA_URL", "http://example.com/?test=5"); instance.init(4711, config, null, null); instance.setTimeStampTokenProviderImplementation(MockedTimeStampTokenProvider.class); // reset mock counters MockedTimeStampTokenProvider.reset(); RequestContext requestContext = new RequestContext(); requestContext.put(RequestContext.TRANSACTION_ID, "0000-100-1"); GenericSignRequest request = new GenericSignRequest(100, "<test100/>".getBytes("UTF-8")); GenericSignResponse response = (GenericSignResponse) instance.processData(request, requestContext); byte[] data = response.getProcessedData(); final String signedXml = new String(data); LOG.debug("signedXml: " + signedXml); // Validation: setup CertStore certStore = CertStore.getInstance("Collection", new CollectionCertStoreParameters(tokenRSA.getCertificateChain(ICryptoToken.PURPOSE_SIGN))); KeyStore trustAnchors = KeyStore.getInstance("JKS"); trustAnchors.load(null, "foo123".toCharArray()); trustAnchors.setCertificateEntry("cert", tokenRSA.getCertificate(ICryptoToken.PURPOSE_SIGN)); CertificateValidationProvider certValidator = new PKIXCertificateValidationProvider(trustAnchors, false, certStore);// ww w . ja v a 2 s .c o m XadesVerificationProfile p = new XadesVerificationProfile(certValidator) .withTimeStampTokenVerifier(new MockedTimeStampVerificationProvider()); XadesVerifier verifier = p.newVerifier(); // Validation: parse final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); final DocumentBuilder builder = factory.newDocumentBuilder(); final Document doc = builder.parse(new ByteArrayInputStream(data)); Element node = doc.getDocumentElement(); XAdESVerificationResult r = verifier.verify(node, new SignatureSpecificVerificationOptions()); LOG.debug("signature form: " + r.getSignatureForm().name()); assertEquals("T", r.getSignatureForm().name()); assertEquals("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", r.getSignatureAlgorithmUri()); // check that a time stamp token was requested assertTrue("Should request a time stamp token", MockedTimeStampTokenProvider.hasRequestedTimeStampToken()); // check that the time stamp token was verified assertTrue("Should try to verify timestamp", MockedTimeStampTokenProvider.hasPerformedTimeStampVerification()); }
From source file:org.viafirma.nucleo.validacion.CRLValidationHandler.java
/** * Metodo encargado de la verificacin de los certificados * //from w ww. j a va 2s . c om * @param certificadoX509 * @throws ExcepcionErrorInterno */ public CodigoError validarCRL(X509Certificate certificadoX509) { try { // 1.- Inicia la factoria de certificados CertificateFactory factoriaCertificados = CertificateFactory.getInstance("X.509", BouncyCastleProvider.PROVIDER_NAME); log.debug("Validando certificado perteneciente a: " + certificadoX509.getIssuerDN()); CertPathValidator validador = CertPathValidator.getInstance("PKIX", BouncyCastleProvider.PROVIDER_NAME); // 2.- Configuracin de los parametros del validador // 2.1.- Para comprobar que el camino de confianza no esta roto, // tengo en cuenta todos los certificados PKIXParameters parametros = new PKIXParameters(certificadosConfianza); // Fecha para la comprobacin de validez. parametros.setDate(new Date()); if (validacionOnline) { // Para la validacin online de del estado de revocacin de los // certificados // ************ // creo un almacen( cache ) de certificados y CRLs para no tener // que conectarme a las crls // en cada validacin // Genero un listado de las CRLS que vamos a utilizar para la // validacin del certificado. List<CRL> listaCRLsCertificadosAlmacenados = new LinkedList<CRL>(); // Aade las crls de los certificados de confianza reconocidos // por Viafirma. // estos certificados son los marcados con el prefijo viafirma_ for (TrustAnchor trustAnchor : certificadosConfianza) { // TODO establecer un sistema de cache eficiente // TODO recuperar solo las crls del certificado en uso. listaCRLsCertificadosAlmacenados .addAll(CRLUtil.getCurrentInstance().getCRLs(trustAnchor.getTrustedCert())); // para cada certificado. } // aado al listado todas las crls del certificado actual. EJ // para el caso de // un certificado de FNMT el certificado personal contiene CN = // CRL1827,OU = FNMT Clase 2 CA,O = FNMT,C = ES listaCRLsCertificadosAlmacenados.addAll(CRLUtil.getCurrentInstance().getCRLs(certificadoX509)); // parametros para la creacin del almacen(cache CRLs) CollectionCertStoreParameters params = new CollectionCertStoreParameters( listaCRLsCertificadosAlmacenados); CertStore almacen = CertStore.getInstance("Collection", params, BouncyCastleProvider.PROVIDER_NAME); parametros.addCertStore(almacen); } else { // No se utilizan las CRLs para la comprobacin de la // revocacin. parametros.setRevocationEnabled(false); } // certificados a validar ( solo 1) List<X509Certificate> certificadosValidar = new ArrayList<X509Certificate>(1); certificadosValidar.add(certificadoX509); // genero el listado de certificados a validar CertPath certPath = factoriaCertificados.generateCertPath(certificadosValidar); // validacin CertPathValidatorResult resultado = validador.validate(certPath, parametros); if (log.isDebugEnabled()) { if (resultado instanceof java.security.cert.PKIXCertPathValidatorResult) { // pintamos el arbol de politicas PolicyNode node = ((java.security.cert.PKIXCertPathValidatorResult) resultado).getPolicyTree(); StringBuffer ruta = new StringBuffer( "Certificado vlido: " + certificadoX509.getSubjectDN().getName()); while (node != null) { ruta.append("-->"); ruta.append(node.getValidPolicy()); if (node.getChildren().hasNext()) { node = node.getChildren().next(); } else { node = null; } } log.info("ruta de validacin: " + ruta); } } return CodigoError.OK_CERTIFICADO_VALIDADO; } catch (CertificateException e) { log.fatal(CodigoError.ERROR_INTERNO, e); return CodigoError.ERROR_INTERNO; } catch (NoSuchProviderException e) { log.fatal(CodigoError.ERROR_INTERNO, e); return CodigoError.ERROR_INTERNO; } catch (NoSuchAlgorithmException e) { log.fatal(CodigoError.ERROR_INTERNO, e); return CodigoError.ERROR_INTERNO; } catch (InvalidAlgorithmParameterException e) { log.fatal(CodigoError.ERROR_VALIDACION_CONFIGURACION_PARAMETRO, e); return CodigoError.ERROR_VALIDACION_CONFIGURACION_PARAMETRO; } catch (CRLException e) { log.fatal(CodigoError.ERROR_VALIDACION_CRL, e); return CodigoError.ERROR_VALIDACION_CRL; } catch (CertPathValidatorException e) { // detectamos el tipo de problema if (e.getMessage().contains(java.security.cert.CertificateExpiredException.class.getName()) || e.getMessage().contains("Certificate revocation after") || e.getMessage().contains("NotAfter") || e.getMessage().contains("certificate expired on")) { log.warn("El certificado esta caducado." + e.getMessage() + " " + certificadoX509.getSubjectDN()); return CodigoError.ERROR_VALIDACION_CERTIFICADO_CADUCADO; } else if (e.getMessage().contains(java.security.SignatureException.class.getName())) { log.warn( "Algunos de los certificados en el camino de certificacin no tiene crl. Algunos de los certificados no se puede validar." + e.getMessage() + " " + certificadoX509.getSubjectDN()); return CodigoError.ERROR_VALIDACION_CRL; } else if (e.getMessage().contains("no valid CRL found")) { log.warn("No se ha podido comprobar la validez del certificado. " + e.getMessage() + " " + certificadoX509.getSubjectDN()); return CodigoError.ERROR_VALIDACION_CRL; } else if (e.getMessage().contains("CertPath not found")) { log.warn("Autoridad de certificacin no reconicida." + e.getMessage() + " " + certificadoX509.getIssuerDN()); return CodigoError.ERROR_VALIDACION_AUTORIDAD_NO_RECONOCIDA; } else { log.warn("Autoridad de certificacin no reconicida." + e.getMessage() + " " + certificadoX509.getIssuerDN()); return CodigoError.ERROR_VALIDACION_AUTORIDAD_NO_RECONOCIDA; } // TODO java.security.cert.CertPathValidatorException: couldn't // validate certificate: // java.security.cert.CertificateNotYetValidException: NotBefore: // Thu Apr 19 19:22:17 CEST 2007 // at // org.bouncycastle.jce.provider.PKIXCertPathValidatorSpi.engineValidate(PKIXCertPathValidatorSpi.java:819) } }
From source file:org.viafirma.util.SendMailUtil.java
public MultiPartEmail buildMessage(String subject, String mailTo, String texto, String htmlTexto, String alias, String password) throws ExcepcionErrorInterno, ExcepcionCertificadoNoEncontrado { try {//w w w. j ava2s . c om // 1.- Preparamos el certificado // Recuperamos la clave privada asociada al alias PrivateKey privateKey = KeyStoreLoader.getPrivateKey(alias, password); if (privateKey == null) { throw new ExcepcionCertificadoNoEncontrado( "No existe una clave privada para el alias '" + alias + "'"); } if (log.isDebugEnabled()) log.info("Firmando el documento con el certificado " + alias); // Recuperamos el camino de confianza asociado al certificado List<Certificate> chain = KeyStoreLoader.getCertificateChain(alias); // Obtenemos los datos del certificado utilizado. X509Certificate certificadoX509 = (X509Certificate) chain.get(0); CertificadoGenerico datosCertificado = CertificadoGenericoFactory.getInstance() .generar(certificadoX509); String emailFrom = datosCertificado.getEmail(); String emailFromDesc = datosCertificado.getCn(); if (StringUtils.isEmpty(emailFrom)) { log.warn("El certificado indicado no tiene un email asociado, No es vlido para firmar emails" + datosCertificado); throw new ExcepcionCertificadoNoEncontrado( "El certificado indicado no tiene un email asociado, No es vlido para firmar emails."); } CertStore certificadosYcrls = CertStore.getInstance("Collection", new CollectionCertStoreParameters(chain), BouncyCastleProvider.PROVIDER_NAME); // 2.- Preparamos el mail MimeBodyPart bodyPart = new MimeBodyPart(); MimeMultipart dataMultiPart = new MimeMultipart(); MimeBodyPart msgHtml = new MimeBodyPart(); if (StringUtils.isNotEmpty(htmlTexto)) { msgHtml.setContent(htmlTexto, Email.TEXT_HTML + "; charset=UTF-8"); } else { msgHtml.setContent("<p>" + htmlTexto + "</p>", Email.TEXT_PLAIN + "; charset=UTF-8"); } // create the message we want signed MimeBodyPart mensajeTexto = new MimeBodyPart(); if (StringUtils.isNotEmpty(texto)) { mensajeTexto.setText(texto, "UTF-8"); } else if (StringUtils.isEmpty(texto)) { mensajeTexto.setText(CadenaUtilities.cleanHtml(htmlTexto), "UTF-8"); } dataMultiPart.addBodyPart(mensajeTexto); dataMultiPart.addBodyPart(msgHtml); bodyPart.setContent(dataMultiPart); // Crea el nuevo mensaje firmado MimeMultipart multiPart = createMultipartWithSignature(privateKey, certificadoX509, certificadosYcrls, bodyPart); // Creamos el mensaje que finalmente sera enviadio. MultiPartEmail mail = createMultiPartEmail(subject, mailTo, emailFrom, emailFromDesc, multiPart, multiPart.getContentType()); return mail; } catch (InvalidAlgorithmParameterException e) { throw new ExcepcionErrorInterno(CodigoError.ERROR_INTERNO, e); } catch (NoSuchAlgorithmException e) { throw new ExcepcionErrorInterno(CodigoError.ERROR_INTERNO, e); } catch (NoSuchProviderException e) { throw new ExcepcionErrorInterno(CodigoError.ERROR_INTERNO, e); } catch (MessagingException e) { throw new ExcepcionErrorInterno(CodigoError.ERROR_INTERNO, e); } catch (CertificateParsingException e) { throw new ExcepcionErrorInterno(CodigoError.ERROR_INTERNO, e); } catch (CertStoreException e) { throw new ExcepcionErrorInterno(CodigoError.ERROR_INTERNO, e); } catch (SMIMEException e) { throw new ExcepcionErrorInterno(CodigoError.ERROR_INTERNO, e); } catch (EmailException e) { throw new ExcepcionErrorInterno(CodigoError.ERROR_INTERNO, e); } }
From source file:org.yawlfoundation.yawl.digitalSignature.DigitalSignature.java
public CMSSignedData SignedData(Element InputDocument) { try {//from w w w . j a v a2s . c om X509Certificate cert = getCertificate(); PrivateKey privatekey = getPrivateKey(); if (privatekey == null) { return null; } else { String Document = PrepareDocumentToBeSign(InputDocument); System.out.println(Document); System.out.println("Certificate loaded"); // define the provider Bouncy castle if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); } //register the user certificate in the collection ArrayList certList = new ArrayList(); certList.add(cert); CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC"); System.out.println("provider loaded"); // create the CMSSignedData CMSSignedDataGenerator signGen = new CMSSignedDataGenerator(); System.out.println("CMS created"); signGen.addSigner(privatekey, cert, CMSSignedDataGenerator.DIGEST_SHA1); signGen.addCertificatesAndCRLs(certs); System.out.println("Signer loaded"); CMSProcessable content = new CMSProcessableByteArray(Document.getBytes()); System.out.println("BytesArray loaded"); // the second variable "true" means that the content will be wrap with the signature return signGen.generate(content, true, "BC"); } } catch (Exception e) { e.printStackTrace(); return null; } }
From source file:org.zuinnote.hadoop.office.format.common.util.CertificateChainVerificationUtil.java
public static boolean verifyCertificateChain(X509Certificate theCertificate, Set<X509Certificate> chainCertificates) throws CertificateException, NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException { // check if we can establish a trust chain if (isSelfSigned(theCertificate)) { LOG.error("Certificate is self-signed - no trust chain can be established with provided truststore"); return false; }/*from ww w. ja v a2s . c o m*/ if (chainCertificates.size() < 2) { LOG.error( "One needs at least three certificates (including certificate used for signing to establish a trust chain. Please check that you included them"); return false; } HashSet<X509Certificate> rootCertificates = new HashSet<>(); HashSet<X509Certificate> subCertificates = new HashSet<>(); subCertificates.add(theCertificate); for (X509Certificate currentCertificate : chainCertificates) { if (CertificateChainVerificationUtil.isSelfSigned(currentCertificate)) { LOG.debug("Root: " + currentCertificate.getSubjectDN().getName()); rootCertificates.add(currentCertificate); } else { LOG.debug("Sub: " + currentCertificate.getSubjectDN().getName()); subCertificates.add(currentCertificate); } } // Configure verification X509CertSelector selector = new X509CertSelector(); selector.setCertificate(theCertificate); CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", "BC"); HashSet<TrustAnchor> trustAnchors = new HashSet<>(); for (X509Certificate currentCertificate : rootCertificates) { trustAnchors.add(new TrustAnchor(currentCertificate, null)); } PKIXBuilderParameters builderParams = new PKIXBuilderParameters(trustAnchors, selector); CertStore subCertStore = CertStore.getInstance("Collection", new CollectionCertStoreParameters(subCertificates), "BC"); builderParams.addCertStore(subCertStore); try { PKIXCertPathBuilderResult result = (PKIXCertPathBuilderResult) builder.build(builderParams); return true; } catch (CertPathBuilderException e) { LOG.error("Exception: ", e); LOG.error("Cannot verify certification chain for " + theCertificate.getSubjectX500Principal()); } return false; }