List of usage examples for java.security.cert CertPath getCertificates
public abstract List<? extends Certificate> getCertificates();
From source file:com.lastdaywaiting.example.kalkan.service.SecureManager.java
private Certificate createCerificateByFile(String fileName, String storeDescript) { CertPath cp = null; try {/*from w w w . java2 s .c om*/ InputStream inputStream = this.getClass().getResourceAsStream(fileName); CertificateFactory certFactory = CertificateFactory.getInstance("X.509", providerName); cp = certFactory.generateCertPath(inputStream, "PKCS7"); inputStream.close(); //IOUtils.closeQuietly(fis); } catch (Exception ex) { throw new RuntimeException( "ORE SIGN: ? ? ? ? '" + fileName + "' ? " + storeDescript + ".", ex); } List<? extends Certificate> certs = cp.getCertificates(); if (certs.size() == 1) { System.out.println(" ? " + fileName + " ? " + storeDescript); return certs.get(0); } else { throw new RuntimeException(" '" + fileName + "' ? " + storeDescript + " 1 ? " + certs.size()); } }
From source file:com.vmware.identity.idm.server.clientcert.IdmCertificatePathValidator.java
/** * Set up sun validator CRL options for revocation checking. * * If revocation is turned on, the following options will be set here: * "com.sun.security.enableCRLDP" to false. Also this function adds CRL's to the provided collection. * * @param certCollection in/out. CRL to be set up for validating the status of the certificate. * @param CertPath target certificate path for validation. */*from w w w . j a v a 2 s. c o m*/ * @throws CertificateRevocationCheckException */ private void setupCRLOptions(Collection<Object> crlCollection, CertPath certPath) throws CertificateRevocationCheckException { /** * Extract or add CRLs to working list of CRLimpl Setup * up revocation check related java property */ if (this.certPolicy.revocationCheckEnabled()) { boolean enableCRLChecking = (this.certPolicy.useOCSP() && !this.certPolicy.useCRLAsFailOver()) ? false : true; //get custom CRL URL customCrlUri = this.certPolicy.getCRLUrl(); if (enableCRLChecking == true && customCrlUri != null) { try { addCRLToWorkingList(customCrlUri.toString(), crlCollection); } catch (CrlDownloadException e) { throw new CertificateRevocationCheckException( "Failed to download CRL from custom CRL URI: " + customCrlUri.toString(), e); } } //get CRLs from certpath CRLDP, use cache if available. Turn off sun security CRLDP checking since we extract them as override if (enableCRLChecking && this.certPolicy.useCertCRL()) { List<? extends java.security.cert.Certificate> certList = certPath.getCertificates(); if (certList == null) { return; } Iterator<? extends java.security.cert.Certificate> it = certList.iterator(); while (it.hasNext()) { try { addCertCRLsToWorkingList((X509Certificate) it.next(), crlCollection); } catch (CertificateRevocationCheckException e) { //Not able to get any of CRLDP from this certificate. Throw if no custom CRL and OCSP is not enabled if (customCrlUri == null && this.certPolicy.useOCSP() == false) { throw new CertificateRevocationCheckException("CRL download failure. ", e); } } } } setThreadLocalSystemProperty("com.sun.security.enableCRLDP", "false"); } //else none of these setting matters. }
From source file:org.apache.ws.security.components.crypto.CryptoBase.java
/** * Construct an array of X509Certificate's from the byte array. * <p/>/*from www.j a v a2 s. co m*/ * * @param data The <code>byte</code> array containing the X509 data * @param reverse If set the first certificate in input data will * the last in the array * @return An array of X509 certificates, ordered according to * the reverse flag * @throws WSSecurityException */ public X509Certificate[] getX509Certificates(byte[] data, boolean reverse) throws WSSecurityException { InputStream in = new ByteArrayInputStream(data); CertPath path = null; try { path = getCertificateFactory().generateCertPath(in); } catch (CertificateException e) { throw new WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE, "parseError", null, e); } List l = path.getCertificates(); X509Certificate[] certs = new X509Certificate[l.size()]; Iterator iterator = l.iterator(); for (int i = 0; i < l.size(); i++) { certs[(reverse) ? (l.size() - 1 - i) : i] = (X509Certificate) iterator.next(); } return certs; }
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 ww .j ava2 s . com * * @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.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/*www . j a v a 2 s . c om*/ * @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.globus.gsi.trustmanager.TrustedCertPathFinder.java
/** * Method that validates the provided cert path to find a trusted certificate in the certificate store. * <p/>/*from w ww . ja v a 2s . c o m*/ * For each certificate i in certPath, it is expected that the i+1 certificate is the issuer of the certificate * path. See CertPath. * <p/> * For each certificate i in certpath, validate signature of certificate i get issuer of certificate i get * certificate i+i ensure that the certificate i+1 is issuer of certificate i If not, throw an exception for * illegal argument validate signature of i+1 Throw exception if it does not validate check if i+1 is a trusted * certificate in the trust store. If so return certpath until i+1 If not, continue; If all certificates in the * certpath have been checked and none exisits in trust store, check if trust store has certificate of issuer of * last certificate in CertPath. If so, return certPath + trusted certificate from trust store If not, throw * an exception for lack of valid trust root. * * @param keyStore The key store containing CA trust root certificates * @param certPath The certpath from which to extract a valid cert path to a trusted certificate. * @return The valid CertPath. * @throws CertPathValidatorException If the CertPath is invalid. */ public static CertPath findTrustedCertPath(KeyStore keyStore, CertPath certPath) throws CertPathValidatorException { // This will be the cert path to return List<X509Certificate> trustedCertPath = new ArrayList<X509Certificate>(); // This is the certs to validate List<? extends Certificate> certs = certPath.getCertificates(); X509Certificate x509Certificate; int index = 0; int certsSize = certs.size(); Certificate certificate = certs.get(index); if (!(certificate instanceof X509Certificate)) { throw new CertPathValidatorException( "Certificate of type " + X509Certificate.class.getName() + " required"); } x509Certificate = (X509Certificate) certificate; while (index < certsSize) { CertPath finalCertPath = isTrustedCert(keyStore, x509Certificate, trustedCertPath); if (finalCertPath != null) { return finalCertPath; } if (index + 1 >= certsSize) { break; } index++; Certificate issuerCertificate = certs.get(index); x509Certificate = checkCertificate(trustedCertPath, x509Certificate, issuerCertificate); } X509CertSelector selector = new X509CertSelector(); selector.setSubject(x509Certificate.getIssuerX500Principal()); Collection<? extends Certificate> caCerts; try { caCerts = KeyStoreUtil.getTrustedCertificates(keyStore, selector); } catch (KeyStoreException e) { throw new CertPathValidatorException(e); } if (caCerts.size() < 1) { throw new CertPathValidatorException("No trusted path can be constructed"); } boolean foundTrustRoot = false; for (Certificate caCert : caCerts) { if (!(caCert instanceof X509Certificate)) { logger.warn("Skipped a certificate: not an X509Certificate"); continue; } try { trustedCertPath.add(checkCertificate(trustedCertPath, x509Certificate, caCert)); // currently the caCert self-signature is not checked // to be consistent with the isTrustedCert() method foundTrustRoot = true; // we found a CA cert that signed the certificate // so we don't need to check any more break; } catch (CertPathValidatorException e) { // fine, just move on to check the next potential CA cert // after the loop we'll check whether any were successful logger.warn("Failed to validate signature of certificate with " + "subject DN '" + x509Certificate.getSubjectDN() + "' against a CA certificate with issuer DN '" + ((X509Certificate) caCert).getSubjectDN() + "'"); } } if (!foundTrustRoot) { throw new CertPathValidatorException("No trusted path can be constructed"); } try { CertificateFactory certFac = CertificateFactory.getInstance("X.509"); return certFac.generateCertPath(trustedCertPath); } catch (CertificateException e) { throw new CertPathValidatorException("Error generating trusted certificate path", e); } }
From source file:org.gluu.oxtrust.ldap.service.SSLService.java
private static X509Certificate[] loadCertificatesAsPkiPathEncoded(InputStream is) throws Exception { try {// w w w . ja v a 2 s . co m CertificateFactory cf = CertificateFactory.getInstance(X509_CERT_TYPE, SECURITY_PROVIDER_BOUNCY_CASTLE); CertPath certPath = cf.generateCertPath(is, PKI_PATH_ENCODING); List<? extends Certificate> certs = certPath.getCertificates(); ArrayList<X509Certificate> loadedCerts = new ArrayList<X509Certificate>(); for (Iterator<? extends Certificate> itr = certs.iterator(); itr.hasNext();) { X509Certificate cert = (X509Certificate) itr.next(); if (cert != null) { loadedCerts.add(cert); } } return loadedCerts.toArray(new X509Certificate[loadedCerts.size()]); } finally { IOUtils.closeQuietly(is); } }
From source file:org.kse.crypto.x509.X509CertUtil.java
private static X509Certificate[] loadCertificatesPkiPath(InputStream is) throws CryptoException { try {/*from ww w . j av a 2s. c o m*/ CertificateFactory cf = CertificateFactory.getInstance(X509_CERT_TYPE, BOUNCY_CASTLE.jce()); CertPath certPath = cf.generateCertPath(is, PKI_PATH_ENCODING); List<? extends Certificate> certs = certPath.getCertificates(); ArrayList<X509Certificate> loadedCerts = new ArrayList<X509Certificate>(); for (Iterator<? extends Certificate> itr = certs.iterator(); itr.hasNext();) { X509Certificate cert = (X509Certificate) itr.next(); if (cert != null) { loadedCerts.add(cert); } } return loadedCerts.toArray(new X509Certificate[loadedCerts.size()]); } catch (CertificateException | NoSuchProviderException e) { throw new CryptoException(res.getString("NoLoadPkiPath.exception.message"), e); } finally { IOUtils.closeQuietly(is); } }
From source file:org.texai.x509.X509Utils.java
/** Generates a certificate path for a signed end-use certificate that cannot be used to sign other certificates, but can be used for authentication * and for message signing./*from ww w . j a v a 2s . c o m*/ * * @param myPublicKey the public key for this certificate * @param issuerPrivateKey the issuer's private key * @param issuerCertificate the issuer's X.509 certificate * @param issuerCertPath the issuer's certificate path * @param domainComponent the domain component, e.g. NodeRuntime * @return a certificate path for a signed end-use certificate * * @throws CertificateParsingException when the certificate cannot be parsed * @throws CertificateEncodingException when the certificate cannot be encoded * @throws NoSuchProviderException when an invalid provider is given * @throws NoSuchAlgorithmException when an invalid algorithm is given * @throws SignatureException when the an invalid signature is present * @throws InvalidKeyException when the given key is invalid * @throws IOException if an input/output error occurs while processing the serial number file * @throws CertificateException when an invalid certificate is present */ public static CertPath generateX509CertificatePath(final PublicKey myPublicKey, final PrivateKey issuerPrivateKey, final X509Certificate issuerCertificate, final CertPath issuerCertPath, final String domainComponent) throws CertificateParsingException, CertificateEncodingException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException, IOException, CertificateException { //Preconditions assert myPublicKey != null : "myPublicKey must not be null"; assert issuerPrivateKey != null : "issuerPrivateKey must not be null"; assert issuerCertificate != null : "issuerCertificate must not be null"; assert issuerCertPath != null : "issuerCertPath must not be null"; final X509Certificate generatedCertificate = generateX509Certificate(myPublicKey, issuerPrivateKey, issuerCertificate, UUID.randomUUID(), domainComponent); final List<Certificate> certificateList = new ArrayList<>(); certificateList.add(generatedCertificate); certificateList.addAll(issuerCertPath.getCertificates()); return generateCertPath(certificateList); }
From source file:org.texai.x509.X509Utils.java
/** Adds an entry to the specified keystore, creating the keystore if it does not already exist. * * @param keyStoreFilePath the file path to the keystore * @param keyStorePassword the keystore's password * @param alias the entry alias/* ww w . ja v a 2s . c o m*/ * @param certPath the certificate path to add * @param privateKey the private key associated with the first certificate in the path * @return the keystore * @throws KeyStoreException * @throws IOException * @throws NoSuchAlgorithmException * @throws CertificateException * @throws NoSuchProviderException */ public static KeyStore addEntryToKeyStore(final String keyStoreFilePath, final char[] keyStorePassword, final String alias, final CertPath certPath, final PrivateKey privateKey) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, NoSuchProviderException { //Preconditions assert keyStoreFilePath != null : "keyStoreFilePath must not be null"; assert !keyStoreFilePath.isEmpty() : "keyStoreFilePath must not be empty"; assert keyStorePassword != null : "keyStorePassword must not be null"; assert alias != null : "alias must not be null"; assert !alias.isEmpty() : "alias must not be empty"; final KeyStore keyStore = X509Utils.findOrCreateKeyStore(keyStoreFilePath, keyStorePassword); final Certificate[] certificateChain = new Certificate[certPath.getCertificates().size() + 1]; for (int i = 0; i < certPath.getCertificates().size(); i++) { certificateChain[i] = certPath.getCertificates().get(i); } certificateChain[certPath.getCertificates().size()] = X509Utils.getRootX509Certificate(); keyStore.setKeyEntry(alias, privateKey, keyStorePassword, certificateChain); keyStore.store(new FileOutputStream(keyStoreFilePath), keyStorePassword); //Postconditions assert keyStore != null : "keyStore must not be null"; return keyStore; }