List of usage examples for java.security.cert PKIXParameters setRevocationEnabled
public void setRevocationEnabled(boolean val)
From source file:org.cesecore.util.CertTools.java
/** * Method to create certificate path and to check it's validity from a list of certificates. The list of certificates should only contain one root * certificate./*from w w w.j a v a2s .c o m*/ * * @param certlist * @return the certificatepath with the root CA at the end * @throws CertPathValidatorException if the certificate chain can not be constructed * @throws InvalidAlgorithmParameterException * @throws NoSuchProviderException * @throws NoSuchAlgorithmException * @throws CertificateException */ public static List<Certificate> createCertChain(Collection<?> certlistin) throws CertPathValidatorException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException, CertificateException { final List<Certificate> returnval = new ArrayList<Certificate>(); Collection<Certificate> certlist = orderCertificateChain(certlistin); // set certificate chain Certificate rootcert = null; ArrayList<Certificate> calist = new ArrayList<Certificate>(); for (Certificate next : certlist) { if (CertTools.isSelfSigned(next)) { rootcert = next; } else { calist.add(next); } } if (calist.isEmpty()) { // only one root cert, no certchain returnval.add(rootcert); } else { // We need a bit special handling for CV certificates because those can not be handled using a PKIX CertPathValidator Certificate test = calist.get(0); if (test.getType().equals("CVC")) { if (calist.size() == 1) { returnval.add(test); returnval.add(rootcert); } else { throw new CertPathValidatorException( "CVC certificate chain can not be of length longer than two."); } } else { // Normal X509 certificates HashSet<TrustAnchor> trustancors = new HashSet<TrustAnchor>(); TrustAnchor trustanchor = null; trustanchor = new TrustAnchor((X509Certificate) rootcert, null); trustancors.add(trustanchor); // Create the parameters for the validator PKIXParameters params = new PKIXParameters(trustancors); // Disable CRL checking since we are not supplying any CRLs params.setRevocationEnabled(false); params.setDate(new Date()); // Create the validator and validate the path CertPathValidator certPathValidator = CertPathValidator .getInstance(CertPathValidator.getDefaultType(), "BC"); CertificateFactory fact = CertTools.getCertificateFactory(); CertPath certpath = fact.generateCertPath(calist); CertPathValidatorResult result = certPathValidator.validate(certpath, params); // Get the certificates validate in the path PKIXCertPathValidatorResult pkixResult = (PKIXCertPathValidatorResult) result; returnval.addAll(certpath.getCertificates()); // Get the CA used to validate this path TrustAnchor ta = pkixResult.getTrustAnchor(); X509Certificate cert = ta.getTrustedCert(); returnval.add(cert); } } return returnval; }
From source file:org.ejbca.extra.db.ExtRAMsgHelper.java
/** * Method used to verify signed data.// www . j a va2 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.ejbca.util.CertTools.java
/** * Check the certificate with CA certificate. * * @param certificate cert to verify//from w w w . java 2 s .c om * @param caCertPath collection of X509Certificate * @return true if verified OK * @throws Exception if verification failed */ public static boolean verify(Certificate certificate, Collection<Certificate> caCertPath) throws Exception { try { ArrayList<Certificate> certlist = new ArrayList<Certificate>(); // Create CertPath certlist.add(certificate); // Add other certs... CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC"); java.security.cert.CertPath cp = cf.generateCertPath(certlist); // Create TrustAnchor. Since EJBCA use BouncyCastle provider, we assume // certificate already in correct order X509Certificate[] cac = (X509Certificate[]) caCertPath.toArray(new X509Certificate[] {}); java.security.cert.TrustAnchor anchor = new java.security.cert.TrustAnchor(cac[0], null); // Set the PKIX parameters java.security.cert.PKIXParameters params = new java.security.cert.PKIXParameters( java.util.Collections.singleton(anchor)); params.setRevocationEnabled(false); java.security.cert.CertPathValidator cpv = java.security.cert.CertPathValidator.getInstance("PKIX", "BC"); java.security.cert.PKIXCertPathValidatorResult result = (java.security.cert.PKIXCertPathValidatorResult) cpv .validate(cp, params); if (log.isDebugEnabled()) { log.debug("Certificate verify result: " + result.toString()); } } catch (java.security.cert.CertPathValidatorException cpve) { throw new Exception( "Invalid certificate or certificate not issued by specified CA: " + cpve.getMessage()); } catch (Exception e) { throw new Exception("Error checking certificate chain: " + e.getMessage()); } return true; }
From source file:org.ejbca.util.CertTools.java
/** * Method to create certificate path and to check it's validity from a list of certificates. * The list of certificates should only contain one root certificate. * * @param certlist//from w ww . j a va2 s . com * @return the certificatepath with the root CA at the end, either collection of Certificate or byte[] (der encoded certs) * @throws CertPathValidatorException if the certificate chain can not be constructed * @throws InvalidAlgorithmParameterException * @throws NoSuchProviderException * @throws NoSuchAlgorithmException * @throws CertificateException */ public static Collection<Certificate> createCertChain(Collection<?> certlistin) throws CertPathValidatorException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException, CertificateException { ArrayList<Certificate> returnval = new ArrayList<Certificate>(); Collection<Certificate> certlist = orderCertificateChain(certlistin); // set certificate chain Certificate rootcert = null; ArrayList<Certificate> calist = new ArrayList<Certificate>(); Iterator<Certificate> iter = certlist.iterator(); while (iter.hasNext()) { Certificate next = iter.next(); if (CertTools.isSelfSigned(next)) { rootcert = next; } else { calist.add(next); } } if (calist.isEmpty()) { // only one root cert, no certchain returnval.add(rootcert); } else { // We need a bit special handling for CV certificates because those can not be handled using a PKIX CertPathValidator Certificate test = calist.get(0); if (test.getType().equals("CVC")) { if (calist.size() == 1) { returnval.add(test); returnval.add(rootcert); } else { throw new CertPathValidatorException( "CVC certificate chain can not be of length longer than two."); } } else { // Normal X509 certificates HashSet<TrustAnchor> trustancors = new HashSet<TrustAnchor>(); TrustAnchor trustanchor = null; trustanchor = new TrustAnchor((X509Certificate) rootcert, null); trustancors.add(trustanchor); // Create the parameters for the validator PKIXParameters params = new PKIXParameters(trustancors); // Disable CRL checking since we are not supplying any CRLs params.setRevocationEnabled(false); params.setDate(new Date()); // Create the validator and validate the path CertPathValidator certPathValidator = CertPathValidator .getInstance(CertPathValidator.getDefaultType(), "BC"); CertificateFactory fact = CertTools.getCertificateFactory(); CertPath certpath = fact.generateCertPath(calist); CertPathValidatorResult result = certPathValidator.validate(certpath, params); // Get the certificates validate in the path PKIXCertPathValidatorResult pkixResult = (PKIXCertPathValidatorResult) result; returnval.addAll(certpath.getCertificates()); // Get the CA used to validate this path TrustAnchor ta = pkixResult.getTrustAnchor(); X509Certificate cert = ta.getTrustedCert(); returnval.add(cert); } } return returnval; }
From source file:org.hyperledger.fabric.sdk.security.CryptoPrimitives.java
boolean validateCertificate(Certificate cert) { boolean isValidated; if (cert == null) { return false; }/*w w w. j a va 2s . c o m*/ try { KeyStore keyStore = getTrustStore(); PKIXParameters parms = new PKIXParameters(keyStore); parms.setRevocationEnabled(false); CertPathValidator certValidator = CertPathValidator.getInstance(CertPathValidator.getDefaultType()); // PKIX ArrayList<Certificate> start = new ArrayList<>(); start.add(cert); CertificateFactory certFactory = CertificateFactory.getInstance(CERTIFICATE_FORMAT); CertPath certPath = certFactory.generateCertPath(start); certValidator.validate(certPath, parms); isValidated = true; } catch (KeyStoreException | InvalidAlgorithmParameterException | NoSuchAlgorithmException | CertificateException | CertPathValidatorException | CryptoException e) { logger.error("Cannot validate certificate. Error is: " + e.getMessage() + "\r\nCertificate" + cert.toString()); isValidated = false; } return isValidated; }
From source file:org.josso.auth.scheme.validation.CRLX509CertificateValidator.java
public void validate(X509Certificate certificate) throws X509CertificateValidationException { try {/*ww w . j a v a2 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 {/* w ww . j a v a2s .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.texai.x509.X509Utils.java
/** Validates the given X.509 certificate path, throwing an exception if the path is invalid. * * @param certPath the given X.509 certificate path, which does not include the trust anchor in contrast to a * certificate chain that does// w ww . j av a2s.com * * @throws InvalidAlgorithmParameterException if an invalid certificate path validation parameter is provided * @throws NoSuchAlgorithmException if an invalid encryption algorithm is specified * @throws CertPathValidatorException if the given x.509 certificate path is invalid */ public static void validateCertificatePath(final CertPath certPath) throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, CertPathValidatorException { //Preconditions assert certPath != null : "certPath must not be null"; final Set<TrustAnchor> trustAnchors = new HashSet<>(); trustAnchors.add(new TrustAnchor(X509Utils.getRootX509Certificate(), null)); // nameConstraints final PKIXParameters params = new PKIXParameters(trustAnchors); params.setSigProvider(BOUNCY_CASTLE_PROVIDER); params.setRevocationEnabled(false); final CertPathValidator certPathValidator = CertPathValidator .getInstance(CertPathValidator.getDefaultType()); certPathValidator.validate(certPath, params); }
From source file:org.viafirma.nucleo.validacion.CRLValidationHandler.java
/** * Metodo encargado de la verificacin de los certificados * /*from www. ja v a2 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) } }
From source file:org.wso2.carbon.security.util.ServerCrypto.java
private boolean validateCertPath(KeyStore ks, Certificate[] certs) throws WSSecurityException { try {/*from ww w. j a v a2 s.co m*/ // Generate cert path java.util.List certList = java.util.Arrays.asList(certs); CertPath path = this.getCertificateFactory().generateCertPath(certList); // Use the certificates in the keystore as TrustAnchors PKIXParameters param = new PKIXParameters(ks); // Do not check a revocation list param.setRevocationEnabled(false); // Verify the trust path using the above settings String provider = properties.getProperty("org.apache.ws.security.crypto.merlin.cert.provider"); CertPathValidator certPathValidator; if (provider == null || provider.length() == 0) { certPathValidator = CertPathValidator.getInstance("PKIX"); } else { certPathValidator = CertPathValidator.getInstance("PKIX", provider); } certPathValidator.validate(path, param); } catch (NoSuchProviderException | NoSuchAlgorithmException | CertificateException | InvalidAlgorithmParameterException | CertPathValidatorException | KeyStoreException ex) { throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { ex.getMessage() }, ex); } return true; }