List of usage examples for java.security.cert CertPathValidator validate
public final CertPathValidatorResult validate(CertPath certPath, CertPathParameters params) throws CertPathValidatorException, InvalidAlgorithmParameterException
From source file:MainClass.java
public static void main(String args[]) throws Exception { CertificateFactory cf = CertificateFactory.getInstance("X.509"); List mylist = new ArrayList(); FileInputStream in = new FileInputStream(args[0]); Certificate c = cf.generateCertificate(in); mylist.add(c);/*from www .j a va 2s . co m*/ CertPath cp = cf.generateCertPath(mylist); Certificate trust = cf.generateCertificate(in); TrustAnchor anchor = new TrustAnchor((X509Certificate) trust, null); PKIXParameters params = new PKIXParameters(Collections.singleton(anchor)); params.setRevocationEnabled(false); CertPathValidator cpv = CertPathValidator.getInstance("PKIX"); PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult) cpv.validate(cp, params); System.out.println(result); }
From source file:MainClass.java
public static void main(String args[]) throws Exception { CertificateFactory cf = CertificateFactory.getInstance("X.509"); List mylist = new ArrayList(); FileInputStream in = new FileInputStream(args[0]); Certificate c = cf.generateCertificate(in); mylist.add(c);/* w w w. j av a 2 s. c om*/ CertPath cp = cf.generateCertPath(mylist); FileInputStream kin = new FileInputStream(args[0]); KeyStore ks = KeyStore.getInstance("JKS"); ks.load(kin, args[1].toCharArray()); PKIXParameters params = new PKIXParameters(ks); params.setRevocationEnabled(false); CertPathValidator cpv = CertPathValidator.getInstance("PKIX"); PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult) cpv.validate(cp, params); PublicKey pbk = result.getPublicKey(); byte[] pkenc = pbk.getEncoded(); BigInteger pk = new BigInteger(pkenc); System.out.println(pk.toString(16)); TrustAnchor anc = result.getTrustAnchor(); X509Certificate xc = anc.getTrustedCert(); System.out.println(xc.getSubjectDN()); System.out.println(xc.getIssuerDN()); }
From source file:Main.java
public static void main(String[] argv) throws Exception { String filename = System.getProperty("java.home") + "/lib/security/cacerts".replace('/', File.separatorChar); FileInputStream is = new FileInputStream(filename); KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); String password = "password"; keystore.load(is, password.toCharArray()); PKIXParameters params = new PKIXParameters(keystore); params.setRevocationEnabled(false);//from ww w . ja v a 2 s . co m CertPathValidator certPathValidator = CertPathValidator.getInstance(CertPathValidator.getDefaultType()); CertPath certPath = null; CertPathValidatorResult result = certPathValidator.validate(certPath, params); PKIXCertPathValidatorResult pkixResult = (PKIXCertPathValidatorResult) result; TrustAnchor ta = pkixResult.getTrustAnchor(); X509Certificate cert = ta.getTrustedCert(); }
From source file:Main.java
public static PKIXCertPathValidatorResult validateCertificate(X509Certificate entity, X509Certificate intermediate, X509Certificate CA) throws Exception { /* KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(null, null);//from w w w .j a va 2 s . c o m String alias = "validationCA"; ks.setCertificateEntry(alias, CA); */ /* KeyStore intermediatesStore = KeyStore.getInstance(KeyStore.getDefaultType()); intermediatesStore.load(null, null); String alias_intermediate = "validationIntermediate"; intermediatesStore.setCertificateEntry(alias_intermediate, intermediate);*//* X509CertSelector target = new X509CertSelector(); target.setCertificate(entity); PKIXBuilderParameters params = new PKIXBuilderParameters(ks, target); ArrayList<X509Certificate> chain = new ArrayList<>(); chain.add(intermediate); chain.add(intermediate); CertStoreParameters intermediates = new CollectionCertStoreParameters(chain); params.addCertStore(CertStore.getInstance("Collection", intermediates)); CertPathBuilder builder = CertPathBuilder.getInstance("PKIX"); *//* * If build() returns successfully, the certificate is valid. More details * about the valid path can be obtained through the PKIXBuilderResult. * If no valid path can be found, a CertPathBuilderException is thrown. *//* PKIXCertPathBuilderResult result = (PKIXCertPathBuilderResult)builder.build(params); return result;*/ CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); CertPath certPath = certificateFactory .generateCertPath(Arrays.asList(new X509Certificate[] { entity, intermediate })); TrustAnchor trustAnchor = new TrustAnchor(CA, null); CertPathValidator cpv = CertPathValidator.getInstance("PKIX"); PKIXParameters pkixParams = new PKIXParameters(Collections.singleton(trustAnchor)); pkixParams.setRevocationEnabled(true); return (PKIXCertPathValidatorResult) cpv.validate(certPath, pkixParams); }
From source file:com.vangent.hieos.services.sts.util.STSUtil.java
/** * * @param cert//from www . j a v a 2s .co m * @param trustStore * @throws STSException */ public static void validateCertificate(X509Certificate cert, KeyStore trustStore) throws STSException { try { // To check the validity of the dates cert.checkValidity(); } catch (CertificateExpiredException ex) { throw new STSException("Certificate expired: " + ex.getMessage()); } catch (CertificateNotYetValidException ex) { throw new STSException("Certificate not yet valid: " + ex.getMessage()); } // Check the chain. try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); List<X509Certificate> mylist = new ArrayList<X509Certificate>(); mylist.add(cert); CertPath cp = cf.generateCertPath(mylist); PKIXParameters params = new PKIXParameters(trustStore); // FIXME: Add revocation checking. params.setRevocationEnabled(false); CertPathValidator cpv = CertPathValidator.getInstance(CertPathValidator.getDefaultType()); PKIXCertPathValidatorResult pkixCertPathValidatorResult = (PKIXCertPathValidatorResult) cpv.validate(cp, params); if (logger.isDebugEnabled()) { logger.debug(pkixCertPathValidatorResult); } } catch (Exception ex) { throw new STSException("Exception while validating Certificate: " + ex.getMessage()); } }
From source file:ch.swisscom.mid.verifier.MobileIdCmsVerifier.java
/** * Validates the specified certificate path incl. OCSP revocation check * //from www . java 2s .c o m * @param truststore * @return true if all certificate is valid * @throws Exception */ private boolean isCertValid(KeyStore truststore) throws Exception { List<X509Certificate> certlist = new ArrayList<X509Certificate>(); certlist.add(signerCert); PKIXParameters params = new PKIXParameters(truststore); // Activate certificate revocation checking params.setRevocationEnabled(true); // Activate OCSP Security.setProperty("ocsp.enable", "true"); // Activate CRLDP System.setProperty("com.sun.security.enableCRLDP", "true"); // Ensure that the ocsp.responderURL property is not set. if (Security.getProperty("ocsp.responderURL") != null) { throw new Exception("The ocsp.responderURL property must not be set"); } CertPathValidator cpv = CertPathValidator.getInstance(CertPathValidator.getDefaultType()); cpv.validate(CertificateFactory.getInstance("X.509").generateCertPath(certlist), params); return true; // No Exception, all fine.. }
From source file:net.sf.dsig.verify.XmldsigVerifier.java
public boolean isCertificatePathValid() throws VerificationException { if (trustAnchors == null) { throw new ConfigurationException("TrustAnchors must be set"); }/*from w w w .j a va2 s . c om*/ try { PKIXParameters parameters = new PKIXParameters(trustAnchors); parameters.setRevocationEnabled(false); CertificateFactory cf = CertificateFactory.getInstance("X.509"); CertPath certPath = cf.generateCertPath(Arrays.asList(getCertificateChain())); CertPathValidator cpv = CertPathValidator.getInstance("PKIX"); PKIXCertPathValidatorResult res = (PKIXCertPathValidatorResult) cpv.validate(certPath, parameters); logger.debug("Certificate path validation succeeded; result=" + res.toString()); return true; } catch (CertPathValidatorException e) { logger.info("Certificate path validation failed", e); return false; } catch (InvalidAlgorithmParameterException e) { throw new ConfigurationException("PKIX algorithm not found; should not happen"); } catch (CertificateException e) { throw new ConfigurationException("X.509 certificate factory not found; should not happen"); } catch (NoSuchAlgorithmException e) { throw new ConfigurationException("PKIX algorithm not found; should not happen"); } }
From source file:com.alfaariss.oa.profile.aselect.ws.security.OACrypto.java
/** * Validate a given certificate chain.// ww w . ja v a 2s . c om * @see Crypto#validateCertPath(java.security.cert.X509Certificate[]) */ public boolean validateCertPath(X509Certificate[] certs) throws WSSecurityException { boolean ok = false; try { // Generate cert path List<X509Certificate> certList = Arrays.asList(certs); CertPath path = this.getCertificateFactory().generateCertPath(certList); HashSet<TrustAnchor> set = new HashSet<TrustAnchor>(); if (certs.length == 1) // Use factory certs { String alias = _factory.getAliasForX509Cert(certs[0].getIssuerDN().getName(), certs[0].getSerialNumber()); if (alias == null) { _logger.debug("Certificate not trusted"); return false; } X509Certificate cert = (X509Certificate) _factory.getCertificate(alias); TrustAnchor anchor = new TrustAnchor(cert, cert.getExtensionValue("2.5.29.30")); set.add(anchor); } else { // Add certificates from the keystore Enumeration aliases = _factory.getAliases(); while (aliases.hasMoreElements()) { String alias = (String) aliases.nextElement(); X509Certificate cert = (X509Certificate) _factory.getCertificate(alias); TrustAnchor anchor = new TrustAnchor(cert, cert.getExtensionValue("2.5.29.30")); set.add(anchor); } } PKIXParameters param = new PKIXParameters(set); param.setRevocationEnabled(false); Provider provider = _factory.getKeyStore().getProvider(); String sProvider = null; CertPathValidator certPathValidator = null; if (provider != null) { sProvider = provider.getName(); } if (sProvider == null || sProvider.length() == 0) { certPathValidator = CertPathValidator.getInstance("PKIX"); } else { certPathValidator = CertPathValidator.getInstance("PKIX", sProvider); } certPathValidator.validate(path, param); ok = true; } catch (NoSuchProviderException e) { _logger.warn("No such provider", e); throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() }, e); } catch (NoSuchAlgorithmException e) { _logger.warn("No such algorithm", e); throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() }, e); } catch (InvalidAlgorithmParameterException e) { _logger.warn("Invalid algorithm param", e); throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() }, e); } catch (CertificateException e) { _logger.warn("Invalid certificate", e); throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() }, e); } catch (ClassCastException e) { _logger.warn("Certificate is not an X509Certificate", e); throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() }, e); } catch (CertPathValidatorException e) { _logger.warn("Could not validate Cert Path", e); throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() }, e); } catch (CryptoException e) { throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() }, e); } return ok; }
From source file:module.signature.util.XAdESValidator.java
/** * @author joao.antunes@tagus.ist.utl.pt adapted it from {@link #validateXMLSignature(String)} * @param streamWithSignature/*from www.j a va 2 s .co m*/ * the {@link InputStream} that has the signature content * @return true if it's valid, false otherwise */ public boolean validateXMLSignature(InputStream streamWithSignature) { try { // get the xsd schema Validator validator = schemaXSD.newValidator(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder parser = dbf.newDocumentBuilder(); ErrorHandler eh = new ErrorHandler() { @Override public void warning(SAXParseException exception) throws SAXException { throw new UnsupportedOperationException("Not supported yet.", exception); } @Override public void error(SAXParseException exception) throws SAXException { throw new UnsupportedOperationException("Not supported yet.", exception); } @Override public void fatalError(SAXParseException exception) throws SAXException { throw new UnsupportedOperationException("Not supported yet.", exception); } }; // parse the document parser.setErrorHandler(eh); Document document = parser.parse(streamWithSignature); // XAdES extension NodeList nlObject = document.getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "Object"); // XMLDSIG NodeList nlSignature = document.getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "Signature"); if (checkSchema) { if (nlObject.getLength() < 1) { return false; } if (nlSignature.getLength() < 1) { return false; } // parse the XML DOM tree againts the XSD schema validator.validate(new DOMSource(nlSignature.item(0))); } if (checkSignature) { // Validate Every Signature Element (including CounterSignatures) for (int i = 0; i < nlSignature.getLength(); i++) { Element signature = (Element) nlSignature.item(i); // String baseURI = fileToValidate.toURL().toString(); XMLSignature xmlSig = new XMLSignature(signature, null); KeyInfo ki = xmlSig.getKeyInfo(); // If signature contains X509Data if (ki.containsX509Data()) { NodeList nlSigningTime = signature.getElementsByTagNameNS(xadesNS, "SigningTime"); Date signingDate = null; if (nlSigningTime.item(0) != null) { StringBuilder xmlDate = new StringBuilder(nlSigningTime.item(0).getTextContent()) .deleteCharAt(22); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); signingDate = simpleDateFormat.parse(xmlDate.toString()); } //verificao OCSP //TODO FENIX-189 joantune: na realidade acho que isto no verifica mesmo a revocao.. a no ser que a keystore indicada seja actualizada regularmente. if (checkRevocation) { //keystore certs cc, raiz estado Security.setProperty("ocsp.enable", "true"); //System.setProperty("com.sun.security.enableCRLDP", "true"); CertificateFactory cf = CertificateFactory.getInstance("X.509"); CertPath certPath = cf .generateCertPath(Collections.singletonList(ki.getX509Certificate())); // TrustAnchor trustA = new TrustAnchor(ki.getX509Certificate(), null); // Set trustAnchors = Collections.singleton(trustA); PKIXParameters params = new PKIXParameters(cartaoCidadaoKeyStore); params.setRevocationEnabled(true); // validar o estado na data da assinatura if (nlSigningTime.item(0) != null) { params.setDate(signingDate); } try { CertPathValidator cpValidator = CertPathValidator.getInstance("PKIX"); CertPathValidatorResult result = cpValidator.validate(certPath, params); //TODO FENIX-196 probably one would want to send a notification here } catch (CertPathValidatorException ex) { return false; } catch (InvalidAlgorithmParameterException ex) { return false; } } // verifica a validade do certificado no momento da assinatura if (checkValidity) { if (nlSigningTime.item(0) != null) { // continue if there is no SigningTime, if CounterSignature isn't XAdES try { ki.getX509Certificate().checkValidity(signingDate); } catch (CertificateExpiredException ex) { return false; } catch (CertificateNotYetValidException ex) { return false; } } } // validate against Certificate Public Key boolean validSignature = xmlSig.checkSignatureValue(ki.getX509Certificate().getPublicKey()); if (!validSignature) { return false; } } // if signature includes KeyInfo KeyValue, also check against it if (ki.containsKeyValue()) { boolean validSignature = xmlSig.checkSignatureValue(ki.getPublicKey()); if (!validSignature) { return false; } } //let's check the SignatureTimeStamp(s) joantune NodeList signatureTimeStamps = signature.getElementsByTagNameNS("*", "SignatureTimeStamp"); Element signatureValue = null; if (signatureTimeStamps.getLength() > 0) { signatureValue = (Element) signature.getElementsByTagNameNS("*", "SignatureValue").item(0); } for (int j = 0; j < signatureTimeStamps.getLength(); j++) { logger.debug("Found a SignatureTimeStamp"); Element signatureTimeStamp = (Element) signatureTimeStamps.item(j); //for now we are ignoring the XMLTimeStamp element, let's iterate through all of the EncapsulatedTimeStamp that we find NodeList encapsulatedTimeStamps = signatureTimeStamp.getElementsByTagNameNS("*", "EncapsulatedTimeStamp"); for (int k = 0; k < encapsulatedTimeStamps.getLength(); k++) { logger.debug("Found an EncapsulatedTimeStamp"); Element encapsulatedTimeStamp = (Element) encapsulatedTimeStamps.item(k); //let's check it // note, we have the timestamptoken, not the whole response, that is, we don't have the status field ASN1Sequence signedTimeStampToken = ASN1Sequence .getInstance(Base64.decode(encapsulatedTimeStamp.getTextContent())); CMSSignedData cmsSignedData = new CMSSignedData( Base64.decode(encapsulatedTimeStamp.getTextContent())); TimeStampToken timeStampToken = new TimeStampToken(cmsSignedData); //let's construct the Request to make sure this is a valid response //let's generate the digest MessageDigest sha1 = MessageDigest.getInstance("SHA-1"); byte[] digest = sha1.digest(signatureValue.getTextContent().getBytes("UTF-8")); //let's make sure the digests are the same if (!Arrays.equals(digest, timeStampToken.getTimeStampInfo().getMessageImprintDigest())) { //TODO probably want to send an e-mail if this happens, as it's clearly a sign of tampering //FENIX-196 logger.debug("Found a different digest in the timestamp!"); return false; } try { //TODO for now we won't use the provided certificates that came with the TST // X509Store certificateStore = (X509Store) timeStampToken.getCertificates(); // JcaDigestCalculatorProviderBuilder builder = new JcaDigestCalculatorProviderBuilder(); // timeStampToken.validate(tsaCert, "BC"); // timeStampToken.validate(new SignerInformationVerifier(new JcaContentVerifierProviderBuilder() // .build(tsaCert), builder.build())); timeStampToken.validate(new SignerInformationVerifier( new JcaContentVerifierProviderBuilder().build(tsaCert), new BcDigestCalculatorProvider())); //let's just verify that the timestamp was done in the past :) - let's give a tolerance of 5 mins :) Date currentDatePlus5Minutes = new Date(); //let's make it go 5 minutes ahead currentDatePlus5Minutes.setMinutes(currentDatePlus5Minutes.getMinutes() + 5); if (!timeStampToken.getTimeStampInfo().getGenTime() .before(currentDatePlus5Minutes)) { //FENIX-196 probably we want to log this! //what the heck, timestamp is done in the future!! (clocks might be out of sync) logger.warn("Found a timestamp in the future!"); return false; } logger.debug("Found a valid TimeStamp!"); //as we have no other timestamp elements in this signature, this means all is ok! :) //(point 5) of g.2.2.16.1.3 on the specs } catch (TSPException exception) { logger.debug("TimeStamp response did not validate", exception); return false; } } } } } } catch (IOException ex) { Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex); return false; } catch (ParserConfigurationException ex) { Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex); return false; } catch (SAXException ex) { Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex); return false; } catch (Exception ex) { Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex); return false; } return true; }
From source file:com.vmware.identity.idm.server.clientcert.IdmCertificatePathValidator.java
/** * Validate the certificate path using a provided OCSP responder configuration. * * @param certPath required// w w w .j a va 2 s. com * @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); } }