List of usage examples for java.security.cert PKIXParameters addCertStore
public void addCertStore(CertStore store)
From source file:com.vmware.identity.idm.server.clientcert.IdmCertificatePathValidator.java
/** * Validate the certificate path using a provided OCSP responder configuration. * * @param certPath required/*from w w w.j av a 2s .co m*/ * @param crlCollection * @param certStore null possible cert store for PKIX param * @param altOCSP null possible * @throws CertificateRevocationCheckException * @throws IdmCertificateRevokedException */ private void validateCertPath(CertPath certPath, Collection<Object> crlCollection, CertStore certStore, AlternativeOCSP altOCSP) throws CertificateRevocationCheckException, IdmCertificateRevokedException { setupOCSPOptions(certPath, altOCSP); PKIXParameters params = createPKIXParameters(crlCollection); if (null != certStore) { params.addCertStore(certStore); } CertPathValidator certPathValidator; try { certPathValidator = CertPathValidator.getInstance("PKIX"); } catch (NoSuchAlgorithmException e) { throw new CertificateRevocationCheckException("Error getting PKIX validator instance:" + e.getMessage(), e); } try { String pkiParam = params.toString(); logger.trace("**Certificate Path Validation Parameters trust anchors **\n" + params.getTrustAnchors().toString() + "\n"); logger.trace("**Certificate Path Validation Parameters **\n" + pkiParam + "\n"); CertPathValidatorResult result = certPathValidator.validate(certPath, params); logger.trace("**Certificate Path Validation Result **\n" + result.toString() + "\n"); } catch (CertPathValidatorException e) { if (e.getReason() == CertPathValidatorException.BasicReason.REVOKED) { throw new IdmCertificateRevokedException("CRL shows certificate status as revoked"); } else if (e.getReason() == CertPathValidatorException.BasicReason.UNDETERMINED_REVOCATION_STATUS) { throw new CertRevocationStatusUnknownException( "CRL checking could not determine certificate status."); } throw new CertificateRevocationCheckException("Certificate path validation failed:" + e.getMessage(), e); } catch (InvalidAlgorithmParameterException e) { throw new CertificateRevocationCheckException( "Certificate validation parameters invalid, could not validate certificate path:" + e.getMessage(), e); } }
From source file:com.vmware.identity.idm.server.clientcert.IdmCertificatePathValidator.java
/** * Create parameters for CertPathValidator using PKIX algorithm. * * The parameter object was defined with given trustStore and CRL collection * @param trustStore2/*from w w w. j a v a 2s .c om*/ * @return non-null PKIXParameters * @throws CertificateRevocationCheckException */ private PKIXParameters createPKIXParameters(Collection<Object> crlCollection) throws CertificateRevocationCheckException { PKIXParameters params = null; try { Validate.notNull(trustStore, "TrustStore can not be null."); params = new PKIXParameters(trustStore); if (this.certPolicy.revocationCheckEnabled()) { params.setRevocationEnabled(true); } else { params.setRevocationEnabled(false); } } catch (KeyStoreException e) { throw new CertificateRevocationCheckException( "Error creating validator parameters: Please check trust store" + e.getMessage(), e); } catch (InvalidAlgorithmParameterException e) { throw new CertificateRevocationCheckException("Error creating validator parameters:" + e.getMessage(), e); } catch (Throwable e) { //have this block in case a new type of error was thrown throw new CertificateRevocationCheckException("Error creating validator parameters:" + e.getMessage(), e); } if (!crlCollection.isEmpty()) { try { CertStore crlStore = CertStore.getInstance("Collection", new CollectionCertStoreParameters(crlCollection)); params.addCertStore(crlStore); } catch (InvalidAlgorithmParameterException e) { throw new CertificateRevocationCheckException( "Error adding CRLs to validating parameters:" + e.getMessage(), e); } catch (NoSuchAlgorithmException e) { throw new CertificateRevocationCheckException( "Error adding CRLs to validating parameters:" + e.getMessage(), e); } } else { logger.debug("Revocation check: CRL list empty"); } // setup certificate policy white list String[] oidWhiteList = this.certPolicy.getOIDs(); if (oidWhiteList != null && oidWhiteList.length > 0) { Set<String> oidSet = new HashSet<String>(); for (String oid : oidWhiteList) { oidSet.add(oid); } params.setInitialPolicies(oidSet); params.setExplicitPolicyRequired(true); } return params; }
From source file:org.apache.synapse.transport.certificatevalidation.pathvalidation.CertificatePathValidator.java
/** * Certificate Path Validation process/* w w w. j a v a2 s . c om*/ * * @throws CertificateVerificationException * if validation process fails. */ public void validatePath() throws CertificateVerificationException { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); CollectionCertStoreParameters params = new CollectionCertStoreParameters(fullCertChain); try { CertStore store = CertStore.getInstance("Collection", params, "BC"); // create certificate path CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC"); CertPath certPath = fact.generateCertPath(certChain); TrustAnchor trustAnchor = new TrustAnchor(fullCertChain.get(fullCertChain.size() - 1), null); Set<TrustAnchor> trust = Collections.singleton(trustAnchor); // perform validation CertPathValidator validator = CertPathValidator.getInstance("PKIX", "BC"); PKIXParameters param = new PKIXParameters(trust); param.addCertPathChecker(pathChecker); param.setRevocationEnabled(false); param.addCertStore(store); param.setDate(new Date()); validator.validate(certPath, param); log.info("Certificate path validated"); } catch (CertPathValidatorException e) { throw new CertificateVerificationException("Certificate Path Validation failed on certificate number " + e.getIndex() + ", details: " + e.getMessage(), e); } catch (Exception e) { throw new CertificateVerificationException("Certificate Path Validation failed", e); } }
From source file:org.apache.synapse.transport.utils.sslcert.pathvalidation.CertificatePathValidator.java
/** * Certificate Path Validation process//from w w w. j a v a2s.c om * * @throws CertificateVerificationException * if validation process fails. */ public void validatePath() throws CertificateVerificationException { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); CollectionCertStoreParameters params = new CollectionCertStoreParameters(fullCertChain); try { CertStore store = CertStore.getInstance("Collection", params, "BC"); // create certificate path CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC"); CertPath certPath = fact.generateCertPath(certChain); TrustAnchor trustAnchor = new TrustAnchor(fullCertChain.get(fullCertChain.size() - 1), null); Set<TrustAnchor> trust = Collections.singleton(trustAnchor); // perform validation CertPathValidator validator = CertPathValidator.getInstance("PKIX", "BC"); PKIXParameters param = new PKIXParameters(trust); param.addCertPathChecker(pathChecker); param.setRevocationEnabled(false); param.addCertStore(store); param.setDate(new Date()); validator.validate(certPath, param); log.debug("Certificate path validated"); } catch (CertPathValidatorException e) { throw new CertificateVerificationException("Certificate Path Validation failed on " + "certificate number " + e.getIndex() + ", details: " + e.getMessage(), e); } catch (Exception e) { throw new CertificateVerificationException("Certificate Path Validation failed", e); } }
From source file:org.apache.ws.security.components.crypto.Merlin.java
/** * Evaluate whether a given certificate chain should be trusted. * Uses the CertPath API to validate a given certificate chain. * * @param certs Certificate chain to validate * @param enableRevocation whether to enable CRL verification or not * @return true if the certificate chain is valid, false otherwise * @throws WSSecurityException/*from w ww .jav a2 s.c o m*/ */ public boolean verifyTrust(X509Certificate[] certs, boolean enableRevocation) throws WSSecurityException { try { // Generate cert path List<X509Certificate> certList = Arrays.asList(certs); CertPath path = getCertificateFactory().generateCertPath(certList); Set<TrustAnchor> set = new HashSet<TrustAnchor>(); if (truststore != null) { Enumeration<String> truststoreAliases = truststore.aliases(); while (truststoreAliases.hasMoreElements()) { String alias = truststoreAliases.nextElement(); X509Certificate cert = (X509Certificate) truststore.getCertificate(alias); if (cert != null) { TrustAnchor anchor = new TrustAnchor(cert, cert.getExtensionValue(NAME_CONSTRAINTS_OID)); set.add(anchor); } } } // // Add certificates from the keystore - only if there is no TrustStore, apart from // the case that the truststore is the JDK CA certs. This behaviour is preserved // for backwards compatibility reasons // if (keystore != null && (truststore == null || loadCACerts)) { Enumeration<String> aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); X509Certificate cert = (X509Certificate) keystore.getCertificate(alias); if (cert != null) { TrustAnchor anchor = new TrustAnchor(cert, cert.getExtensionValue(NAME_CONSTRAINTS_OID)); set.add(anchor); } } } PKIXParameters param = new PKIXParameters(set); param.setRevocationEnabled(enableRevocation); if (enableRevocation && crlCertStore != null) { param.addCertStore(crlCertStore); } // Verify the trust path using the above settings String provider = getCryptoProvider(); CertPathValidator validator = null; if (provider == null || provider.length() == 0) { validator = CertPathValidator.getInstance("PKIX"); } else { validator = CertPathValidator.getInstance("PKIX", provider); } validator.validate(path, param); return true; } catch (java.security.NoSuchProviderException e) { throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() }, e); } catch (java.security.NoSuchAlgorithmException e) { throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() }, e); } catch (java.security.cert.CertificateException e) { throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() }, e); } catch (java.security.InvalidAlgorithmParameterException e) { throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() }, e); } catch (java.security.cert.CertPathValidatorException e) { throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() }, e); } catch (java.security.KeyStoreException e) { throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() }, e); } catch (NullPointerException e) { // NPE thrown by JDK 1.7 for one of the test cases throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() }, e); } }
From source file:org.ejbca.extra.db.ExtRAMsgHelper.java
/** * Method used to verify signed data./* ww w . ja v a 2 s .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.josso.auth.scheme.validation.CRLX509CertificateValidator.java
public void validate(X509Certificate certificate) throws X509CertificateValidationException { try {//from ww w.j av a 2 s. c o m 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 {/*from ww w.j a v a2s. c om*/ 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.viafirma.nucleo.validacion.CRLValidationHandler.java
/** * Metodo encargado de la verificacin de los certificados * /*w w w. j a va 2 s.c o m*/ * @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) } }